#!/usr/bin/env python3
"""Write a desk reply for the phone to poll. Usage:
  desk_reply.py 'your words'
  desk_reply.py --no-voice 'silent text only'
"""
from __future__ import annotations

import json
import subprocess
import sys
import urllib.request
from pathlib import Path

ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))
from serve_last_click import write_reply_md  # noqa: E402


def main() -> None:
    args = sys.argv[1:]
    want_voice = True
    if args and args[0] == "--no-voice":
        want_voice = False
        args = args[1:]
    text = " ".join(args).strip()
    if not text:
        print("usage: desk_reply.py [--no-voice] <reply text>")
        sys.exit(1)

    try:
        req = urllib.request.Request(
            "http://127.0.0.1:8765/api/reply",
            data=json.dumps({"text": text, "from": "eve-local"}).encode(),
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        with urllib.request.urlopen(req, timeout=3) as r:
            print(r.read().decode())
    except Exception:
        ts = write_reply_md(text)
        print(f"wrote latest_reply.md time={ts}")

    if want_voice:
        try:
            r = subprocess.run(
                [sys.executable, str(ROOT / "desk_eve_voice.py"), text],
                capture_output=True,
                text=True,
                timeout=120,
            )
            if r.returncode == 0:
                print(r.stdout.strip() or "eve voice ok")
            else:
                print("eve voice failed:", (r.stderr or r.stdout)[:300], file=sys.stderr)
        except Exception as e:
            print(f"eve voice error: {e}", file=sys.stderr)


if __name__ == "__main__":
    main()
