#!/usr/bin/env python3
"""SessionStart hook (matcher: startup|clear).

If HANDOFF.md exists at the project root, inject it into the fresh
session via additionalContext so work resumes without manual steps.
Never blocks the session: exits 0 on any error.
"""

import json
import os
import sys
import time

MAX_BYTES = 64 * 1024


def main() -> None:
    data = json.load(sys.stdin)
    root = os.environ.get("CLAUDE_PROJECT_DIR") or data.get("cwd") or os.getcwd()
    path = os.path.join(root, "HANDOFF.md")
    if not os.path.isfile(path):
        return
    age_h = (time.time() - os.path.getmtime(path)) / 3600
    with open(path, encoding="utf-8", errors="replace") as f:
        body = f.read(MAX_BYTES)
    ctx = (
        f"[context-rollover] HANDOFF.md found at the project root "
        f"(last modified {age_h:.1f}h ago). It is the handoff from the previous "
        "session - resume from it. Read 'Next Concrete Step' and continue there. "
        "Briefly confirm to the user that you resumed from HANDOFF.md and state "
        "the next step. If the user's first message is unrelated to this handoff, "
        "or it looks stale, say so and ask whether to delete HANDOFF.md.\n\n"
        "----- HANDOFF.md -----\n" + body
    )
    print(
        json.dumps(
            {
                "hookSpecificOutput": {
                    "hookEventName": "SessionStart",
                    "additionalContext": ctx,
                }
            }
        )
    )


if __name__ == "__main__":
    try:
        main()
    except Exception:
        pass
    sys.exit(0)
