#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Licensed under AGPL-3.0.
# See LICENSE file for details.
"""Gemini CLI BeforeTool hook — wraps brain_query.py output for Gemini's JSON protocol.

FIX: Was hardcoding --query "pre-write check" for every invocation.
Now extracts context from hook stdin JSON (file path or command) like
the Claude hook does.
"""
import json
import subprocess
import sys
from pathlib import Path

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

# Extract query from hook event (Gemini passes JSON on stdin)
query = "pre-write check"
try:
    hook_input = json.loads(sys.stdin.read())
    # Try to get file path from tool input
    tool_input = hook_input.get("tool_input", {})
    file_path = tool_input.get("file_path", "") or tool_input.get("path", "")
    command = tool_input.get("command", "")
    if file_path:
        p = Path(file_path)
        query = f"{p.stem} {p.parent.name}"
    elif command:
        query = command[:80]
except Exception:
    pass  # Fall back to default query

result = subprocess.run(
    [sys.executable, str(ROOT / "pulse" / "brain" / "brain_query.py"),
     "--query", query],
    capture_output=True, text=True, timeout=10, cwd=str(ROOT),
    encoding="utf-8", errors="replace",
)
brain = result.stdout.strip() if result.stdout else ""
# Always approve — brain is advisory context injection only.
# Blocking is handled by the separate anti_pattern_gate.py hook.
output = {"decision": "approve"}
if brain and brain != "No brain results.":
    output["hookSpecificOutput"] = {"additionalContext": f"[BRAIN] {brain[:500]}"}
json.dump(output, sys.stdout)
