#!/usr/bin/env python3
"""UserPromptSubmit hook — inject project graph path on the first prompt. Fail-open.

First prompt per session: emits hookSpecificOutput with additionalContext.
Subsequent prompts: emits {} (no-op).
"""
import os
import sys
import json
import subprocess

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import hook_io


def main():
    inp = hook_io.read_input()
    session_id = inp.session_id or "unknown"
    cwd = inp.cwd or os.getcwd()

    flag_file = f"/tmp/memory-context-injected-{session_id}"
    if os.path.exists(flag_file):
        print("{}")
        return
    try:
        open(flag_file, "a").close()
    except Exception:
        pass

    context = ""
    try:
        r = subprocess.run(
            ["git", "-C", cwd, "rev-parse", "--show-toplevel"],
            capture_output=True, text=True,
        )
        project_root = r.stdout.strip() if r.returncode == 0 else ""
    except Exception:
        project_root = ""

    if project_root:
        project_graph = os.path.join(project_root, "graphify-out", "graph.json")
        if os.path.isfile(project_graph):
            context = "## Project Graph\n\nProject graph: %s\n" % project_graph

    output = json.dumps({
        "hookSpecificOutput": {
            "hookEventName": "UserPromptSubmit",
            "additionalContext": context,
        }
    })
    print(output)


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"[session-context] error: {e}", file=sys.stderr)
    sys.exit(0)
