#!/usr/bin/env python3
"""Speak a confirmation with cached OpenChamber Kokoro TTS."""

from __future__ import annotations

import hashlib
import json
import os
import re
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path

ENV_FILE = Path.home() / ".config/hey-player/agent-tool.env"
CACHE_DIR = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "hey-player" / "tts"
STATE_DIR = Path.home() / ".local/state/hey-player"
SAY_LOG = STATE_DIR / "say.log"
RECENT_FILE = STATE_DIR / "recent.json"
DUPLICATE_WINDOW_SECS = 15.0
DEFAULT_ORIGIN = "http://127.0.0.1:57123"
MODEL = "kokoro-en-v0_19"


def log(message: str) -> None:
    line = f"hey-player-say: {message}"
    print(line, file=sys.stderr, flush=True)
    try:
        STATE_DIR.mkdir(parents=True, exist_ok=True)
        with SAY_LOG.open("a", encoding="utf-8") as handle:
            handle.write(f"{time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime())} {line}\n")
    except OSError:
        pass


def was_recently_spoken(key: str) -> bool:
    now = time.time()
    try:
        entries = json.loads(RECENT_FILE.read_text(encoding="utf-8"))
        if not isinstance(entries, dict):
            entries = {}
    except (OSError, json.JSONDecodeError):
        entries = {}

    entries = {
        str(saved_key): float(saved_at)
        for saved_key, saved_at in entries.items()
        if isinstance(saved_at, (int, float)) and now - float(saved_at) < DUPLICATE_WINDOW_SECS
    }
    duplicate = key in entries
    entries[key] = now
    try:
        STATE_DIR.mkdir(parents=True, exist_ok=True)
        RECENT_FILE.write_text(json.dumps(entries), encoding="utf-8")
    except OSError:
        pass
    return duplicate


def read_env_file() -> dict[str, str]:
    result: dict[str, str] = {}
    try:
        text = 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 openchamber_origin() -> str:
    sources = (os.environ, read_env_file())
    for source in sources:
        url = source.get("OPENCHAMBER_AGENT_TOOL_URL", "")
        if not url:
            continue
        parsed = urllib.parse.urlsplit(url)
        if parsed.scheme and parsed.netloc:
            return f"{parsed.scheme}://{parsed.netloc}"
    return DEFAULT_ORIGIN


def synthesize(text: str, speaker_id: int, speed: float) -> bytes:
    payload = json.dumps(
        {
            "text": text,
            "model": MODEL,
            "speakerId": speaker_id,
            "speed": speed,
        }
    ).encode("utf-8")

    url = f"{openchamber_origin()}/api/dictation/tts/speak"
    request = urllib.request.Request(
        url,
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST",
    )

    try:
        with urllib.request.urlopen(request, timeout=60) as response:
            audio = response.read()
            content_type = response.headers.get("Content-Type", "")
    except urllib.error.HTTPError as exc:
        detail = exc.read().decode("utf-8", "replace")[:300]
        raise SystemExit(f"OpenChamber TTS returned HTTP {exc.code}: {detail}") from exc
    except urllib.error.URLError as exc:
        raise SystemExit(f"Could not reach OpenChamber TTS: {exc}") from exc

    if content_type.startswith("application/json") or audio.lstrip().startswith(b"{"):
        raise SystemExit(f"OpenChamber TTS failed: {audio.decode('utf-8', 'replace')[:300]}")
    return audio


def main() -> None:
    text = " ".join(sys.argv[1:]).strip() or sys.stdin.read().strip()
    if not text:
        raise SystemExit("No text to speak")

    try:
        speaker_id = int(os.environ.get("HEY_PLAYER_TTS_SPEAKER", "0"))
    except ValueError:
        speaker_id = 0
    try:
        speed = float(os.environ.get("HEY_PLAYER_TTS_SPEED", "1.0"))
    except ValueError:
        speed = 1.0

    canonical = re.sub(r"\s+", " ", text).strip()
    key_source = f"{canonical.lower()}|speaker={speaker_id}|speed={speed}"
    digest = hashlib.sha256(key_source.encode("utf-8")).hexdigest()[:24]
    CACHE_DIR.mkdir(parents=True, exist_ok=True)
    cache_file = CACHE_DIR / f"{digest}.wav"

    no_play = os.environ.get("HEY_PLAYER_TTS_NO_PLAY") == "1"

    def play() -> None:
        if no_play:
            return
        if was_recently_spoken(digest):
            log("suppressed duplicate within 15s")
            return
        subprocess.run(["pw-play", str(cache_file)], check=True)

    if cache_file.is_file() and cache_file.stat().st_size > 44:
        log("cache hit")
        play()
        return

    log("cache miss; synthesizing")
    audio = synthesize(text, speaker_id, speed)
    with tempfile.NamedTemporaryFile(dir=CACHE_DIR, suffix=".tmp", delete=False) as tmp:
        tmp.write(audio)
        tmp_path = Path(tmp.name)
    os.replace(tmp_path, cache_file)
    play()


if __name__ == "__main__":
    main()
