#!/usr/bin/env python3
"""SessionStart and PreCompact hook: one part of one level of this identity's start text per hook command.

    session-start --context map 1/1                   the memory map, printed as is, after a note on any CLAUDE.md that
                                                      still names a skill under the plugin's old name, and then the
                                                      Skill tool call that gives the index
    session-start --context personal N/M              part N of M of the personal core, as additionalContext
    session-start --context compact 1/1               PreCompact of the main agent: logs the compaction before the
                                                      SessionStart that follows it, and prints nothing; a compaction
                                                      precomputed beside the turn and then dropped is logged too

The index is not put in: the recall skill gives all of it, past the cap on each hook's output. When ownpast
does not answer, the hook starts it through the plugin's CLI once and asks again; without a token it prints nothing.
"""

from __future__ import annotations

import json
import os
import sys

import ownpast_hook

LEVELS = ("map", "personal", "compact")
# the plugin's name before 0.6; a CLAUDE.md written then names its skills this way
OLD_SKILL_PREFIX = "whaat:"
CLAUDE_MD_NAMES = ("CLAUDE.md", "CLAUDE.local.md", os.path.join(".claude", "CLAUDE.md"))


def main():
    args = sys.argv[1:]
    if args[:1] != ["--context"] or len(args) not in (2, 3) or args[1] not in LEVELS:
        sys.exit(__doc__)
    part, parts = (int(n) for n in (args[2] if len(args) == 3 else "1/1").split("/"))
    try:
        event = json.load(sys.stdin)
    except ValueError:
        event = {}
    if not isinstance(event, dict):
        event = {}
    cwd = event.get("cwd") or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()
    if args[1] == "map":
        print_old_skill_names(cwd)
    payload = {
        "level": args[1],
        "part": part,
        "parts": parts,
        "session": event.get("session_id") or "",
        "source": event.get("source") or "",
        "cli": ownpast_hook.CLI,
    }
    if args[1] == "compact" and event.get("agent_id"):
        return
    started = ownpast_hook.call("/api/v1/memory/recall/start", payload)
    if args[1] == "compact" and started is not None:
        return
    if started is None and ownpast_hook.lookup("TOKEN") and ownpast_hook.ensure_server():
        started = ownpast_hook.call("/api/v1/memory/recall/start", payload)
    text = started and started.get("text")
    if args[1] == "compact" or not text:
        return
    if started.get("additional_context"):
        print(json.dumps({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": text}},
                         ensure_ascii=False))
    else:
        print(text + ownpast_hook.INDEX_CALL)


def claude_md_files(cwd):
    """The CLAUDE.md files a session in cwd loads: the config's own, then each folder's from cwd up to the root."""
    config = os.environ.get("CLAUDE_CONFIG_DIR") or os.path.expanduser("~/.claude")
    found = [os.path.join(os.path.expanduser(config), "CLAUDE.md")]
    folder = os.path.abspath(cwd)
    while True:
        found += [os.path.join(folder, name) for name in CLAUDE_MD_NAMES]
        parent = os.path.dirname(folder)
        if parent == folder:
            return found
        folder = parent


def print_old_skill_names(cwd):
    """A CLAUDE.md from before 0.6 names the skills `whaat:<name>`; tell the agent their current names."""
    named = []
    for path in claude_md_files(cwd):
        try:
            with open(path, encoding="utf-8") as handle:
                if OLD_SKILL_PREFIX in handle.read():
                    named.append(path)
        except (OSError, UnicodeDecodeError):
            continue
    if named:
        print(
            f"The plugin whaat is now ownpast. Where {', '.join(named)} names a skill `whaat:<name>`, use "
            "`ownpast:<name>`: the memory-recall rule's skill is `ownpast:memory-recall`. `ownpast connect` rewrites "
            "the rule; every other line stays the user's to change.\n"
        )


if __name__ == "__main__":
    main()
