"""Claude Code PostToolUse hook — tracks the active project.

Reads tool input JSON from stdin, extracts file paths, finds the git root,
and writes to ~/.trace/active_project.

Install as a hook or run directly:
    echo '{"tool_input":{"file_path":"/some/repo/file.py"}}' | trace-hook
"""
from __future__ import annotations

import json
import re
import sys
from pathlib import Path

from . import TRACE_DIR, ACTIVE_PROJECT_FILE


def _extract_path(data: dict) -> str | None:
    """Extract a file path from hook input JSON."""
    inp = data.get("tool_input", {})

    # Direct file_path field (Read, Edit, Write)
    path = inp.get("file_path") or inp.get("path")
    if path and path.startswith("/"):
        return path

    # Bash command — extract first absolute path
    command = inp.get("command", "")
    if command:
        matches = re.findall(r"(/[^\s;|&\"']+)", command)
        if matches:
            return matches[0]

    return None


def _find_git_root(path: str) -> Path | None:
    """Walk up from path to find the git root."""
    p = Path(path)
    if p.is_file():
        p = p.parent
    while p != p.parent:
        if (p / ".git").exists():
            return p
        p = p.parent
    return None


def main() -> None:
    """Entry point for the hook."""
    try:
        data = json.load(sys.stdin)
    except (json.JSONDecodeError, EOFError):
        return

    path = _extract_path(data)
    if not path:
        return

    root = _find_git_root(path)
    if not root:
        return

    # Only write if changed
    try:
        current = ACTIVE_PROJECT_FILE.read_text().strip()
        if current == str(root):
            return
    except OSError:
        pass

    TRACE_DIR.mkdir(parents=True, exist_ok=True)
    ACTIVE_PROJECT_FILE.write_text(str(root) + "\n")


if __name__ == "__main__":
    main()
