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

Used for both BeforeAgent (session boot) and BeforeTool (file writes).
Always outputs {"decision": "approve", "hookSpecificOutput": {"additionalContext": ...}}
so Gemini gets brain context injected. Never blocks — all errors fall through to approve.

Default query "agent startup recent" fires on BeforeAgent boot.
For BeforeTool, query is overridden with the target file path for context-aware lookup.
"""
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)
# Default works for both BeforeAgent (boot context) and BeforeTool (write context)
query = "agent startup recent"
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

try:
    result = subprocess.run(
        [sys.executable, str(ROOT / "pulse" / "brain" / "brain_query.py"),
         "--query", query, "--brief"],
        capture_output=True, text=True, timeout=10, cwd=str(ROOT),
        encoding="utf-8", errors="replace",
    )
    brain = result.stdout.strip() if result.stdout else ""
except Exception:
    brain = ""
# 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)
