#!/usr/bin/env python3
"""Manually capture one voice command (GNOME shortcut fallback)."""

from __future__ import annotations

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

RUNTIME_DIR = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) / "hey-player"
INJECT = Path.home() / ".local/bin/hey-player-inject"
RECORD_SECS = 6.0
WAIT_SECS = 12.0


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


def main() -> None:
    try:
        status = run(["voxtype", "status"], timeout=5.0).stdout.strip()
    except (subprocess.SubprocessError, OSError):
        status = "unknown"
    if status != "idle":
        raise SystemExit(f"voxtype is {status}; not starting another recording")

    RUNTIME_DIR.mkdir(parents=True, exist_ok=True)
    path = RUNTIME_DIR / f"manual-{time.time_ns()}.txt"
    path.unlink(missing_ok=True)

    run(["voxtype", "record", "start", f"--file={path}"])
    time.sleep(RECORD_SECS)
    try:
        run(["voxtype", "record", "stop"], timeout=10.0)
    except subprocess.SubprocessError:
        pass

    deadline = time.monotonic() + WAIT_SECS
    text = ""
    while time.monotonic() < deadline:
        try:
            text = path.read_text(encoding="utf-8").strip()
        except FileNotFoundError:
            text = ""
        if text:
            break
        time.sleep(0.2)
    path.unlink(missing_ok=True)

    if not text:
        raise SystemExit("No transcript captured")
    text = re.sub(r"\s+", " ", text).strip()
    run([str(INJECT), text], timeout=30.0)


if __name__ == "__main__":
    main()
