#!/usr/bin/env python3
from __future__ import annotations
"""
Codex notify wrapper for CodexBar.

Codex's `notify` command is reliably invoked by the app when a turn ends. This
wrapper preserves an optional downstream notifier command and also posts a
short-lived Codex attention event to the local companion.
"""

import json
import os
import subprocess
import sys

import attention_hook


def _post_codex_attention(stdin_text: str) -> None:
    try:
        payload = json.loads(stdin_text) if stdin_text.strip() else {}
        if not isinstance(payload, dict):
            payload = {}
    except json.JSONDecodeError:
        payload = {"message": stdin_text.strip()} if stdin_text.strip() else {}

    payload.setdefault("event", "Notification")
    payload.setdefault("cwd", os.getcwd())
    attention_hook.post_attention(
        attention_hook.build_attention_payload("Codex", payload),
        os.environ.get("CODEXBAR_ATTENTION_URL", attention_hook.DEFAULT_URL).strip()
        or attention_hook.DEFAULT_URL,
    )


def _run_downstream(args: list[str], stdin_text: str) -> int:
    if not args:
        return 0
    try:
        completed = subprocess.run(args, input=stdin_text, text=True, timeout=10, check=False)
        return completed.returncode
    except Exception as exc:
        print(f"[CodexBar notify] downstream failed: {exc}", file=sys.stderr)
        return 0


def main(argv: list[str] | None = None) -> int:
    args = list(sys.argv[1:] if argv is None else argv)
    if args and args[0] == "--":
        args = args[1:]

    stdin_text = sys.stdin.read()
    try:
        _post_codex_attention(stdin_text)
    except Exception as exc:
        print(f"[CodexBar notify] attention post failed: {exc}", file=sys.stderr)

    return _run_downstream(args, stdin_text)


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