"""PostToolUse hook that prompts Claude to label unlabeled chatmap messages."""

import json
import sys

from ..discovery import discover_chatmap

MAX_UNLABELED_TO_SHOW = 5


def main() -> None:
    try:
        event = json.load(sys.stdin)
    except Exception:
        sys.exit(0)

    # Avoid infinite loop: skip if this tool call is chatmap-related
    tool_name = event.get("tool_name", "")
    tool_input = event.get("tool_input", {})
    if tool_name == "Bash":
        cmd = tool_input.get("command", "")
        if "chatmap" in cmd:
            sys.exit(0)

    map_file = discover_chatmap()
    if not map_file:
        sys.exit(0)

    try:
        data = json.loads(map_file.read_text())
    except Exception:
        sys.exit(0)

    messages = data.get("messages", [])
    unlabeled = [
        (i + 1, m) for i, m in enumerate(messages)
        if isinstance(m, dict) and not m.get("label")
    ]

    if not unlabeled:
        sys.exit(0)

    # Show the last few unlabeled
    recent = unlabeled[-MAX_UNLABELED_TO_SHOW:]
    lines = ["Label the following unlabeled chatmap messages using:"]
    lines.append("statusline-chatmap update <id> --label \"<label>\" --description \"<description>\"")
    lines.append("")
    for idx, msg in recent:
        prefix = msg.get("prefix", "")
        role = msg.get("role", "?")
        lines.append(f"  {idx}. [{role}] {prefix}")

    context = "\n".join(lines)
    print(json.dumps({
        "hookSpecificOutput": {
            "hookEventName": "PostToolUse",
            "additionalContext": context,
        }
    }))
    sys.exit(0)


if __name__ == "__main__":
    main()
