#!/usr/bin/env python3
"""SubagentStart hook: a subagent gets the identity's `reach: every-agent` core files and memory map as
additionalContext, and then the Skill tool call that gives the index.

This is the only start event a subagent runs. The text is split on line ends across several hook commands (part N of
M), each under CAP. The index is not put in: the recall skill gives all of it. Without a token or a server it prints
nothing.

    subagent-start N/M
"""

from __future__ import annotations

import json
import re
import sys

import ownpast_hook

CAP = 9500
HEAD = "[memory] for this subagent, part {part}/{shown}:\n"
# what a part may hold of the text: its head and, on the last part, the index call come on top
ROOM = CAP - len(HEAD.format(part=99, shown=99)) - len("\n" + ownpast_hook.INDEX_CALL)
# each every-agent core file starts on a line of its own path; the memory map follows the last one
CORE_FILE = re.compile(r"^\(personal:core/(.+\.md)\)$", re.M)
MAP_HEAD = "## Memory map\n"


def parts(text: str, size: int) -> list[str]:
    chunks, current = [], ""
    for line in text.splitlines(keepends=True):
        if current and len(current) + len(line) > size:
            chunks.append(current)
            current = ""
        current += line
    return [*chunks, current] if current else chunks


def cut_off(text: str, shown: int) -> str:
    """The line that ends the last hook part when the text runs past the hooks: an open call for each core file not
    shown in full."""
    starts = [(m.start(), m.group(1)) for m in CORE_FILE.finditer(text)]
    map_at = text.rfind(MAP_HEAD)
    ends = [start for start, _ in starts[1:]] + [map_at if map_at >= 0 else len(text)]
    cut = [name for (_, name), end in zip(starts, ends) if end > shown]
    if not cut:
        return "[memory] the end of the memory map does not fit the hooks; the call below gives the memory index.\n"
    return (
        "[memory] the every-agent core does not fit the hooks; before your first reply, open each core file it cut,"
        " one Skill tool call per file:\n"
        + "".join(
            f"  call the Skill tool with skill `ownpast:memory-recall` and args"
            f' `open file=personal:core/{name} because="subagent start: core" purpose=load`\n'
            for name in cut
        )
    )


def with_cut_off(text: str, chunk: str, before: int) -> str:
    """The last part with its cut-off line, lines dropped from its end until both fit under the cap."""
    lines = chunk.splitlines(keepends=True)
    while True:
        kept = "".join(lines)
        line = cut_off(text, before + len(kept))
        if len(kept) + len("\n" + line) <= ROOM or len(lines) == 1:
            return kept + "\n" + line
        lines.pop()


def main():
    try:
        part, total = (int(n) for n in sys.argv[1].split("/"))
    except (IndexError, ValueError):
        return
    core = ownpast_hook.call("/api/v1/memory/recall/subagent-core")
    text = core and core.get("text")
    if not text:
        return
    chunks = parts(text, ROOM)
    shown = min(len(chunks), total)
    if part > shown:
        return
    chunk = chunks[part - 1]
    if part == shown and len(chunks) > shown:
        chunk = with_cut_off(text, chunk, sum(len(c) for c in chunks[: shown - 1]))
    if part == shown:
        chunk += "\n" + ownpast_hook.INDEX_CALL
    head = HEAD.format(part=part, shown=shown)
    print(json.dumps({"hookSpecificOutput": {"hookEventName": "SubagentStart", "additionalContext": head + chunk}},
                     ensure_ascii=False))


if __name__ == "__main__":
    main()
