#!/usr/bin/env python3
"""Transcribe an audio file through the Personality Psychic live API.

    pip install websockets
    python transcribe_file.py --host gx10-0241.tail491cd0.ts.net --key pp_... call.wav --language ar

It converts the file to 16 kHz mono 16-bit PCM with ffmpeg (any format ffmpeg reads), opens wss://<host>/v1/listen, sends the
consent message, waits for a slot, streams the audio in real time (--speed 4 streams it four times faster than real time),
prints the lines as they arrive and, at the end, the final transcript with who spoke. Exit code 0 means lines came back.

You, as the caller, state with --acknowledged that every person in the recording knows it is recorded and transcribed and has
agreed. Without it the script refuses to run: recording people secretly is not allowed on this service.
"""
import argparse
import asyncio
import json
import ssl
import subprocess
import sys

import websockets

FRAME_BYTES = 640                                   # 20 ms of 16 kHz mono int16


def pcm(path: str) -> bytes:
    """The file as 16 kHz mono signed 16-bit little-endian PCM."""
    r = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-f", "s16le", "-ar", "16000", "-ac", "1", "-"],
                       capture_output=True)
    if r.returncode or not r.stdout:
        sys.exit("ffmpeg could not read " + path + ": " + r.stderr.decode(errors="replace")[:300])
    return r.stdout


async def run(a) -> int:
    audio = pcm(a.file)
    ctx = ssl.create_default_context()
    if a.insecure:                                      # a box with its own certificate on the LAN
        ctx.check_hostname, ctx.verify_mode = False, ssl.CERT_NONE
    lines: dict[int, dict] = {}                         # start_ms -> line; "replaced" is the truth, "transcript" the fast first read

    async with websockets.connect(f"wss://{a.host}/v1/listen", additional_headers={"Authorization": f"Bearer {a.key}"},
                                  ssl=ctx, max_size=None) as ws:
        await ws.send(json.dumps({"type": "consent", "acknowledged": True, "language": a.language, "live_analysis": False}))
        while True:                                     # wait for a slot
            m = json.loads(await ws.recv())
            if m["type"] == "slot_ready":
                await ws.send(json.dumps({"type": "go"}))
            elif m["type"] == "queued":
                print(f"queued: position {m.get('position')} of {m.get('waiting')}", file=sys.stderr)
            elif m["type"] == "ready":
                print("ready, session", m.get("session"), file=sys.stderr)
                break
            elif m["type"] == "error":
                sys.exit("error: " + str(m.get("detail")))

        async def send():
            step = FRAME_BYTES * 5                      # 100 ms chunks
            for i in range(0, len(audio), step):
                await ws.send(audio[i:i + step])
                await asyncio.sleep(0.1 / a.speed)
            await ws.send(json.dumps({"type": "stop"}))

        sender = asyncio.create_task(send())
        stopped = None
        async for raw in ws:
            m = json.loads(raw)
            t = m.get("type")
            if t == "transcript":
                lines[m["start_ms"]] = m
                print(f"  {m['start_ms'] / 1000:7.1f}s  {m.get('speaker') or '?':>4}  {m['text']}")
            elif t == "replaced":
                for s in m.get("removed", []):
                    lines.pop(s, None)
                for ln in m.get("lines", []):
                    lines[ln["start_ms"]] = ln
            elif t == "speakers":
                for ln in m.get("lines", []):
                    if ln.get("start_ms") in lines:
                        lines[ln["start_ms"]] = {**lines[ln["start_ms"]], **ln}
            elif t == "error":
                print("error:", m.get("detail"), file=sys.stderr)
                if m.get("fatal"):
                    break
            elif t == "stopped":
                stopped = m
                break
        sender.cancel()

    print("\nFinal transcript:")
    for k in sorted(lines):
        ln = lines[k]
        print(f"[{k / 1000:6.1f}s] {ln.get('speaker') or '?'}: {ln['text']}")
    if stopped:
        print("\ncall totals:", json.dumps({k: v for k, v in stopped.items() if k != 'type'}, ensure_ascii=False))
    return 0 if lines else 1


def main() -> None:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("file")
    p.add_argument("--host", required=True, help="the server's host name, no scheme")
    p.add_argument("--key", required=True, help="an API key (pp_...) from your account page")
    p.add_argument("--language", required=True, choices=["ar", "en"])   # required by the server too
    p.add_argument("--speed", type=float, default=1.0, help="1 = real time; 4 = four times faster")
    p.add_argument("--insecure", action="store_true", help="skip certificate checks (a LAN box with its own certificate)")
    p.add_argument("--acknowledged", action="store_true",
                   help="everyone in the recording knows it is recorded and transcribed and has agreed")
    a = p.parse_args()
    if not a.acknowledged:
        sys.exit("Refusing to run without --acknowledged: confirm that everyone in the recording knows and has agreed.")
    sys.exit(asyncio.run(run(a)))


if __name__ == "__main__":
    main()
