#!/usr/bin/env python3
"""PostToolUse (Bash) and UserPromptSubmit hook of ownpast:memory-recall: puts an opened memory into the context.

A tool result reaches the model as data; hook context arrives as a separate note from the harness, so the memory a
recall opens comes as a note. Only an `opened: <file> -> <path>` line or an index answer's header reaches the server;
any other Bash call costs no request.
"""

from __future__ import annotations

import json
import re
import sys

import ownpast_hook

OPENED = re.compile(r"^opened: (\S+) -> (/.+\.md)$", re.M)
PART = re.compile(r"^index ([0-9a-f]{12}) part (\d+)/(\d+)\b", re.M)
UNCHANGED = re.compile(r"^index ([0-9a-f]{12}) unchanged since \S+ \((\d+) parts\)", re.M)


def index_notes(event, stdout):
    """Each index answer in this output checked against what this agent itself read, as correcting lines."""
    answers = [(m.group(1), int(m.group(2)), int(m.group(3)), False) for m in PART.finditer(stdout)]
    answers += [(m.group(1), None, int(m.group(2)), True) for m in UNCHANGED.finditer(stdout)]
    notes = []
    for digest, part, parts, unchanged in answers:
        checked = ownpast_hook.call(
            "/api/v1/memory/recall/seen",
            {
                "session": event.get("session_id") or "",
                "agent": event.get("agent_id") or "",
                "digest": digest,
                "part": part,
                "parts": parts,
                "unchanged": unchanged,
            },
        )
        if checked and checked.get("note"):
            notes.append(checked["note"])
    return notes


def post_tool_use(event):
    # The acknowledgement lines decide, not the command text: a call through a variable or a loop names no
    # `ownpast memory open` at all.
    response = event.get("tool_response")
    stdout = response.get("stdout", "") if isinstance(response, dict) else str(response or "")
    notes = index_notes(event, stdout)
    opened = OPENED.findall(stdout)
    framed = opened and ownpast_hook.call(
        "/api/v1/memory/recall/frame",
        {
            "session": event.get("session_id") or "",
            "agent": event.get("agent_id") or "",
            "opened": [{"file": rel, "path": path} for rel, path in opened],
            "force": "force=1" in (event.get("tool_input") or {}).get("command", ""),
        },
    )
    context = "\n".join([*notes, *([framed["context"]] if framed and framed.get("context") else [])])
    if not context:
        return None
    return {"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": context}}


def user_prompt_submit(event):
    if not ownpast_hook.lookup("TOKEN"):
        return None
    return {"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": (
        "Memory: before you reply, call the Skill tool with skill `ownpast:memory-recall` and args "
        "`index task=\"<what this message asks for>\"`, and open each "
        "memory whose trigger matches. Pass known=<digest> from an index you read every part of and still see; "
        "with none in sight, leave known out.")}}


def main():
    try:
        event = json.load(sys.stdin)
    except ValueError:
        return
    handler = {"PostToolUse": post_tool_use, "UserPromptSubmit": user_prompt_submit}.get(event.get("hook_event_name"))
    output = handler(event) if handler else None
    if output:
        print(json.dumps(output, ensure_ascii=False))


if __name__ == "__main__":
    main()
