#!/usr/bin/env python3
from __future__ import annotations
"""
Forward Claude/Codex hook events to the CodexBar companion.

Usage in a hook command:
    python3 /path/to/CodexBar-ESP32/companion/attention_hook.py Codex

The hook JSON is read from stdin. Failures are logged to stderr but exit 0 so
CodexBar never blocks the agent whose state it is observing.
"""

import json
import os
import sys
import urllib.error
import urllib.request

DEFAULT_URL = "http://127.0.0.1:7842/attention"


def build_attention_payload(provider: str, hook_input: dict) -> dict:
    event = (
        hook_input.get("hook_event_name")
        or hook_input.get("hookEventName")
        or hook_input.get("event")
        or ""
    )
    cwd = hook_input.get("cwd") or os.getcwd()
    session_id = hook_input.get("session_id") or hook_input.get("sessionId") or ""
    payload = {
        "provider": provider,
        "event": event,
        "session_id": session_id,
        "cwd": cwd,
    }
    last_assistant_message = hook_input.get("last_assistant_message") or hook_input.get("lastAssistantMessage")
    if last_assistant_message:
        payload["last_assistant_message"] = last_assistant_message
    message = hook_input.get("message") or hook_input.get("notification_message")
    if message:
        payload["message"] = message
    return payload


def post_attention(payload: dict, url: str) -> None:
    body = json.dumps(payload).encode()
    req = urllib.request.Request(
        url,
        data=body,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=2) as resp:
        resp.read()


def main(argv: list[str] | None = None) -> int:
    args = list(sys.argv[1:] if argv is None else argv)
    if not args:
        print("usage: attention_hook.py <Claude|Codex>", file=sys.stderr)
        return 0

    provider = args[0]
    url = os.environ.get("CODEXBAR_ATTENTION_URL", DEFAULT_URL).strip() or DEFAULT_URL

    try:
        raw = sys.stdin.read()
        hook_input = json.loads(raw) if raw.strip() else {}
        if not isinstance(hook_input, dict):
            raise ValueError("hook input must be a JSON object")
        post_attention(build_attention_payload(provider, hook_input), url)
    except (OSError, ValueError, json.JSONDecodeError, urllib.error.URLError) as e:
        print(f"[CodexBar attention hook] {e}", file=sys.stderr)

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
