#!/usr/bin/env python3
"""
PostToolUse Hook: Track all tool operations to SCRATCHPAD.md.

Logs file edits, bash commands, and other significant operations
for mission progress tracking.
"""

import json
import sys
import os
from datetime import datetime
from pathlib import Path

# Tools to track
TRACKED_TOOLS = {
    "Edit": "edited",
    "Write": "wrote",
    "Bash": "ran",
    "Read": "read",
    "Glob": "searched",
    "Grep": "grepped",
    "Task": "spawned",
}

# Tools to ignore (too noisy)
IGNORED_TOOLS = {
    "TaskList",
    "TaskGet",
    "TaskUpdate",
    "TaskCreate",
}

def get_grid_dir():
    """Get the .grid directory path."""
    project_dir = os.environ.get("CLAUDE_PROJECT_DIR", os.getcwd())
    return Path(project_dir) / ".grid"

def log_to_scratchpad(message):
    """Append a log entry to SCRATCHPAD.md."""
    scratchpad_path = get_grid_dir() / "SCRATCHPAD.md"

    if not scratchpad_path.parent.exists():
        return

    timestamp = datetime.now().strftime("%H:%M:%S")

    try:
        with open(scratchpad_path, 'a') as f:
            f.write(f"\n[{timestamp}] {message}")
    except Exception:
        pass

def format_bash_command(command):
    """Format bash command for logging (truncate if long)."""
    if not command:
        return "command"

    # Remove newlines and extra whitespace
    command = ' '.join(command.split())

    # Truncate long commands
    if len(command) > 80:
        return command[:77] + "..."

    return command

def format_file_path(path):
    """Format file path for logging (show just filename if long)."""
    if not path:
        return "file"

    p = Path(path)

    # If path is very long, just show filename
    if len(str(path)) > 60:
        return f".../{p.name}"

    return str(path)

def main():
    # Read tool context from stdin
    try:
        stdin_data = sys.stdin.read()
        if stdin_data.strip():
            context = json.loads(stdin_data)
        else:
            context = {}
    except json.JSONDecodeError:
        context = {}

    tool_name = context.get("tool_name", "")
    tool_input = context.get("tool_input", {})
    tool_output = context.get("tool_output", "")

    # Skip ignored tools
    if tool_name in IGNORED_TOOLS:
        sys.exit(0)

    # Skip untracked tools
    if tool_name not in TRACKED_TOOLS:
        sys.exit(0)

    action = TRACKED_TOOLS[tool_name]

    # Format message based on tool type
    if tool_name == "Edit":
        file_path = format_file_path(tool_input.get("file_path"))
        old_str = tool_input.get("old_string", "")[:30]
        log_to_scratchpad(f"EDIT: {action} {file_path}")

    elif tool_name == "Write":
        file_path = format_file_path(tool_input.get("file_path"))
        content_len = len(tool_input.get("content", ""))
        log_to_scratchpad(f"WRITE: {action} {file_path} ({content_len} chars)")

    elif tool_name == "Bash":
        command = format_bash_command(tool_input.get("command"))
        log_to_scratchpad(f"BASH: {command}")

    elif tool_name == "Read":
        file_path = format_file_path(tool_input.get("file_path"))
        log_to_scratchpad(f"READ: {file_path}")

    elif tool_name == "Glob":
        pattern = tool_input.get("pattern", "")
        log_to_scratchpad(f"GLOB: {pattern}")

    elif tool_name == "Grep":
        pattern = tool_input.get("pattern", "")[:40]
        log_to_scratchpad(f"GREP: {pattern}")

    elif tool_name == "Task":
        prompt = tool_input.get("prompt", "")[:50]
        log_to_scratchpad(f"SPAWN: {prompt}...")

    sys.exit(0)

if __name__ == "__main__":
    main()
