#!/usr/bin/env python3
"""Send a Hey Player transcript into the dedicated OpenChamber voice session."""

from __future__ import annotations

import json
import os
import re
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path

CONFIG_DIR = Path.home() / ".config" / "hey-player"
SESSION_FILE = CONFIG_DIR / "session-id"
FALLBACK_ENV_FILE = CONFIG_DIR / "agent-tool.env"


def log(message: str) -> None:
    print(f"hey-player-inject: {message}", file=sys.stderr, flush=True)


def read_session_id() -> str:
    try:
        value = SESSION_FILE.read_text(encoding="utf-8").strip()
    except OSError as exc:
        raise SystemExit(f"Cannot read {SESSION_FILE}: {exc}") from exc
    if not value:
        raise SystemExit(f"Empty session id in {SESSION_FILE}")
    return value


def environ_from_openchamber() -> dict[str, str]:
    """Read the managed agent-tool connection from the running OpenChamber app."""
    for proc in Path("/proc").iterdir():
        if not proc.name.isdigit():
            continue
        try:
            cmdline = (proc / "cmdline").read_bytes().split(b"\0")
        except OSError:
            continue
        if not cmdline or not cmdline[0].endswith(b"/openchamber"):
            continue
        if any(b"--type=" in arg for arg in cmdline[1:]):
            continue
        try:
            raw = (proc / "environ").read_bytes()
        except OSError:
            continue
        env: dict[str, str] = {}
        for item in raw.split(b"\0"):
            if not item or b"=" not in item:
                continue
            key, value = item.split(b"=", 1)
            env[key.decode("utf-8", "replace")] = value.decode("utf-8", "replace")
        if env.get("OPENCHAMBER_AGENT_TOOL_URL") and env.get("OPENCHAMBER_AGENT_TOOL_TOKEN"):
            return env
    return {}


def read_fallback_env() -> dict[str, str]:
    result: dict[str, str] = {}
    try:
        text = FALLBACK_ENV_FILE.read_text(encoding="utf-8")
    except OSError:
        return result
    for line in text.splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        result[key.strip()] = value.strip()
    return result


def get_connection() -> tuple[str, str]:
    env = environ_from_openchamber() or read_fallback_env()
    url = env.get("OPENCHAMBER_AGENT_TOOL_URL", "")
    token = env.get("OPENCHAMBER_AGENT_TOOL_TOKEN", "")
    if not url or not token:
        raise SystemExit("OpenChamber agent-tool connection is unavailable")
    return url, token


def clean_transcript(raw: str) -> str:
    text = raw.strip()
    text = re.sub(r"\s+", " ", text)
    text = re.sub(r"^(?:hey|hay)\s+play(?:\s*(?:er|ers))?\s*[,:]?\s*", "", text, flags=re.IGNORECASE)
    text = re.sub(r"^er\s+", "", text, flags=re.IGNORECASE)
    text = text.strip(" \"'")
    return text


def main() -> None:
    raw = sys.argv[1] if len(sys.argv) > 1 else sys.stdin.read()
    text = clean_transcript(raw)
    if not text:
        raise SystemExit("Empty transcript; nothing to inject")

    session_id = read_session_id()
    url, token = get_connection()
    prompt = f"Hey Player: {text}"
    payload = {
        "input": {
            "action": "session.send",
            "sessionId": session_id,
            "prompt": prompt,
        },
        "sessionID": session_id,
        "callID": f"hey-player-{time.time_ns()}",
        "tool": "openchamber",
    }
    request = urllib.request.Request(
        url,
        data=json.dumps(payload).encode("utf-8"),
        headers={
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json",
        },
        method="POST",
    )
    try:
        with urllib.request.urlopen(request, timeout=15) as response:
            body = response.read().decode("utf-8", "replace").strip()
    except urllib.error.HTTPError as exc:
        detail = exc.read().decode("utf-8", "replace")[:500]
        raise SystemExit(f"OpenChamber returned HTTP {exc.code}: {detail}") from exc
    except urllib.error.URLError as exc:
        raise SystemExit(f"Could not reach OpenChamber: {exc}") from exc

    try:
        result = json.loads(body)
    except json.JSONDecodeError as exc:
        raise SystemExit(f"Invalid response from OpenChamber: {body[:300]}") from exc
    if result.get("ok") is not True:
        raise SystemExit(f"OpenChamber rejected the prompt: {body[:500]}")

    log(f"injected: {text}")


if __name__ == "__main__":
    main()
