#!/usr/bin/env python3
"""PostToolUse hook: run pine_dup_check on any .pine file that was just written/edited.

Reads the Claude hook JSON payload from stdin. Exits 0 silently for non-.pine files.
Outputs a block decision if duplicates are found so Claude is notified immediately.
"""
import json
import subprocess
import sys
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parent.parent

data = json.load(sys.stdin)
file_path = data.get("tool_input", {}).get("file_path", "")

if not file_path.endswith(".pine"):
    sys.exit(0)

dup_result = subprocess.run(
    [sys.executable, str(PROJECT_ROOT / "tools" / "check_pine_duplicates.py"), file_path],
    capture_output=True,
    text=True,
)

budget_result = subprocess.run(
    [sys.executable, str(PROJECT_ROOT / "tools" / "check_pine_plot_budget.py"), file_path],
    capture_output=True,
    text=True,
)

reasons = []
if dup_result.returncode != 0:
    reasons.append(f"Duplicate variables:\n{dup_result.stdout.strip()}")
if budget_result.returncode != 0:
    reasons.append(f"Plot budget exceeded:\n{budget_result.stdout.strip()}")

if reasons:
    print(json.dumps({
        "decision": "block",
        "reason": "\n\n".join(reasons),
    }))
