#!/usr/bin/env python3
"""echo_hook_session_start.py — SessionStart hook: self-firing cold-start load.

The two behaviours the skill cares most about (load at session start, reflect at
session end) used to depend entirely on the model remembering to do them — scope
drift and the inbox backlog are the residue of that discipline failing. This hook
makes loading deterministic: on session start it runs the canonical `echo.py load`
and hands the output to the model as additionalContext.

Contract (a hook must NEVER break a session):
  * always exits 0 — any failure degrades to a one-line note or to silence;
  * fires only on `startup` / `clear` (resume & compact already carry context);
  * NOT CONFIGURED (exit 78) becomes a short instruction to run the first-run flow,
    not an error;
  * output is capped so a huge vault can't blow up the context window.
"""
from __future__ import annotations

import contextlib
import io
import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))

MAX_CONTEXT = 16000  # chars of load output forwarded into the session context


def main() -> int:
    try:
        payload = json.load(sys.stdin)
    except Exception:  # noqa: BLE001
        payload = {}
    if payload.get("source", "startup") not in ("startup", "clear"):
        return 0

    header = ("[echo-memory] Cold-start memory load (SessionStart hook). Reconcile per "
              "the echo-memory skill: check inbox depth and confirm the scope still "
              "matches this session's request before working.\n\n")
    buf = io.StringIO()
    try:
        import echo
        with contextlib.redirect_stdout(buf):
            rc = echo.cmd_load(brief=True)  # token-budgeted digest; /echo-load stays full
        text = buf.getvalue()
        if rc == 78:
            context = ("[echo-memory] ECHO is NOT CONFIGURED on this machine. Before "
                       "doing memory work, ask the operator for their echo-memory config "
                       "(owner/endpoint/key) and install it via `echo.py config import "
                       "<file>` — see the skill's First-run section.")
        elif rc == 0 and text.strip():
            if len(text) > MAX_CONTEXT:
                text = text[:MAX_CONTEXT] + "\n[... load output truncated by the hook ...]"
            context = header + text
        else:
            context = ("[echo-memory] `echo.py load` returned nothing usable "
                       f"(exit {rc}) — run /echo-doctor if memory seems unavailable.")
    except Exception as exc:  # noqa: BLE001 — never break session start
        context = (f"[echo-memory] SessionStart load skipped ({exc}). The vault may be "
                   "unreachable; proceed without memory and mention it once if relevant.")

    print(json.dumps({"hookSpecificOutput": {
        "hookEventName": "SessionStart",
        "additionalContext": context,
    }}, ensure_ascii=False))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
