#!/home/user/.local/share/hey-player/venv/bin/python
"""Continuous 'Hey Player' wake-word listener using Vosk grammar mode."""

from __future__ import annotations

import json
import os
import re
import subprocess
import sys
import time
from pathlib import Path

import vosk

MODEL_PATH = Path.home() / ".local/share/hey-player/vosk-model-small-en-us-0.15"
SAMPLE_RATE = 16000
CHUNK_BYTES = 4000  # 125 ms of 16 kHz s16 mono
VOICE_SESSION = "Hey Player voice commands"
COOLDOWN_SECS = 8.0
COMMAND_RECORD_SECS = 6.0
TRANSCRIPT_TIMEOUT_SECS = 15.0

WAKE_PHRASES = (
    "hey player",
    "hay player",
    "hey players",
    "hey play er",
)
WAKE_PREFIXES = (
    "hey play",
    "hay play",
)
GRAMMAR = json.dumps(list(WAKE_PHRASES) + ["[unk]"])

RUNTIME_DIR = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) / "hey-player"

SAY = Path.home() / ".local/bin/hey-player-say"
INJECT = Path.home() / ".local/bin/hey-player-inject"

vosk.SetLogLevel(-1)


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


def normalize(text: str) -> str:
    return re.sub(r"\s+", " ", re.sub(r"[^a-z ]", " ", text.lower())).strip()


def is_wake(text: str) -> bool:
    normalized = normalize(text)
    return any(phrase in normalized for phrase in WAKE_PHRASES)


def is_wake_start(text: str) -> bool:
    normalized = normalize(text)
    return any(normalized.startswith(prefix) for prefix in WAKE_PREFIXES)


CONFIRMATION_RULES = (
    (("pause",), "Pausing the music."),
    (("stop",), "Stopping the music."),
    (("resume", "continue"), "Resuming the music."),
    (("next", "skip"), "Playing the next track."),
    (("previous", "prev", "back"), "Playing the previous track."),
    (("dark techno", "dark club", "techno"), "Playing dark techno music from Jellyfin."),
    (("epic", "cinematic"), "Playing epic music from Jellyfin."),
    (("soft", "calm", "relax"), "Playing soft music from Jellyfin."),
    (("synth", "synthwave"), "Playing synth music from Jellyfin."),
)


def confirmation_for(text: str) -> str:
    normalized = normalize(text)
    normalized = re.sub(r"^(?:hey|hay) play(?: er| ers)?\s+", "", normalized)

    volume = re.search(r"\bvolume\s+(\d{1,3})\b", normalized)
    if volume:
        value = int(volume.group(1))
        if 0 <= value <= 100:
            return f"Setting volume to {value} percent."

    for needles, confirmation in CONFIRMATION_RULES:
        if any(needle in normalized for needle in needles):
            return confirmation
    return "Sorry, I didn't catch a playable command."


def run_quiet(args: list[str], timeout: float = 15.0) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        args,
        check=True,
        capture_output=True,
        text=True,
        timeout=timeout,
    )


def wait_for_transcript(path: Path) -> str:
    deadline = time.monotonic() + TRANSCRIPT_TIMEOUT_SECS
    stop_at = time.monotonic() + COMMAND_RECORD_SECS
    stopped = False
    while time.monotonic() < deadline:
        try:
            text = path.read_text(encoding="utf-8").strip()
        except FileNotFoundError:
            text = ""
        if text:
            return re.sub(r"\s+", " ", text).strip()
        if not stopped and time.monotonic() >= stop_at:
            try:
                run_quiet(["voxtype", "record", "stop"], timeout=10.0)
            except (subprocess.SubprocessError, OSError) as exc:
                log(f"could not stop recording: {exc}")
            stopped = True
        time.sleep(0.2)
    raise TimeoutError("voxtype did not produce a transcript in time")


def handle_wake(now: float) -> None:
    started = now
    log("wake phrase detected")
    RUNTIME_DIR.mkdir(parents=True, exist_ok=True)

    stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(now))
    transcript_path = RUNTIME_DIR / f"command-{stamp}-{time.time_ns() % 100000}.txt"
    transcript_path.unlink(missing_ok=True)

    try:
        run_quiet(["voxtype", "record", "start", f"--file={transcript_path}"], timeout=15.0)
    except (subprocess.SubprocessError, OSError) as exc:
        log(f"voxtype record start failed: {exc}")
        return
    log(f"recording started after {time.monotonic() - started:.2f}s")

    try:
        text = wait_for_transcript(transcript_path)
    except TimeoutError as exc:
        log(str(exc))
        return

    if not text:
        log("empty transcript")
        return

    log(f"transcript after {time.monotonic() - started:.2f}s: {text}")
    confirmation = confirmation_for(text)
    log(f"confirmation: {confirmation}")

    # Speak immediately and let the agent execute at the same time.
    try:
        subprocess.Popen(
            [str(SAY), confirmation],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            start_new_session=True,
        )
        log(f"confirmation started after {time.monotonic() - started:.2f}s")
    except OSError as exc:
        log(f"could not start confirmation: {exc}")

    try:
        run_quiet([str(INJECT), text], timeout=30.0)
    except subprocess.CalledProcessError as exc:
        detail = (exc.stderr or exc.stdout or "").strip()
        log(f"injection failed: {detail or exc}")
    except (subprocess.SubprocessError, OSError) as exc:
        log(f"injection failed: {exc}")
    else:
        log(f"injected after {time.monotonic() - started:.2f}s")

    transcript_path.unlink(missing_ok=True)


def main() -> None:
    if not MODEL_PATH.is_dir():
        raise SystemExit(f"Missing Vosk model at {MODEL_PATH}")

    model = vosk.Model(str(MODEL_PATH))
    recognizer = vosk.KaldiRecognizer(model, SAMPLE_RATE, GRAMMAR)

    capture = subprocess.Popen(
        [
            "pw-record",
            "--rate",
            str(SAMPLE_RATE),
            "--channels",
            "1",
            "--format",
            "s16",
            "--raw",
            "-",
        ],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    assert capture.stdout is not None

    last_trigger = 0.0
    log("listening for Hey Player")

    try:
        while True:
            chunk = capture.stdout.read(CHUNK_BYTES)
            if not chunk:
                stderr = capture.stderr.read().decode("utf-8", "replace") if capture.stderr else ""
                raise RuntimeError(f"pw-record stopped: {stderr.strip()}")
            if not recognizer.AcceptWaveform(chunk):
                partial = json.loads(recognizer.PartialResult() or "{}").get("partial", "")
                if not partial or not is_wake_start(partial):
                    continue
            else:
                result = json.loads(recognizer.Result() or "{}")
                text = result.get("text", "")
                if not text or not is_wake(text):
                    continue

            now = time.monotonic()
            if now - last_trigger < COOLDOWN_SECS:
                log("ignoring wake phrase inside cooldown")
                continue
            last_trigger = now
            recognizer.Reset()
            handle_wake(now)
            recognizer.Reset()
    except KeyboardInterrupt:
        log("stopping")
    finally:
        capture.terminate()
        try:
            capture.wait(timeout=5)
        except subprocess.TimeoutExpired:
            capture.kill()


if __name__ == "__main__":
    main()
