"""Heli tekstiks jutusta.ee API-ga (ElevenLabs-ühilduv). Võti: SDR/secrets/jutusta_api_key.txt (ei lähe kunagi blogisse).

Kasutus: python transcribe.py heli.wav [--lang et|en|auto] [--diarize] [--out fail.txt]
Väljund: tekst stdout'i (+ faili), JSON kõrvale <heli>.jutusta.json (sõnad ajatemplitega).
Piirid: inline fail max 100 MB. Meie klipid on 1–20 MB.
"""
import argparse, json, mimetypes, os, sys, urllib.request, uuid
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
API = "https://jutusta.ee/api/v1/speech-to-text"


def api_key():
    f = ROOT / "secrets" / "jutusta_api_key.txt"
    if not f.exists():
        sys.exit("puudub secrets\\jutusta_api_key.txt")
    return f.read_text(encoding="utf-8-sig").strip()


def transcribe(path, lang="et", diarize=False):
    boundary = "----jutusta" + uuid.uuid4().hex
    fields = {"model_id": "scribe_v1", "language_code": lang, "diarize": "true" if diarize else "false",
              "timestamps_granularity": "word"}
    body = b""
    for k, v in fields.items():
        body += f"--{boundary}\r\nContent-Disposition: form-data; name=\"{k}\"\r\n\r\n{v}\r\n".encode()
    mime = mimetypes.guess_type(path)[0] or "application/octet-stream"
    body += (f"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{os.path.basename(path)}\"\r\n"
             f"Content-Type: {mime}\r\n\r\n").encode() + Path(path).read_bytes() + b"\r\n"
    body += f"--{boundary}--\r\n".encode()
    req = urllib.request.Request(API, data=body, method="POST", headers={
        "xi-api-key": api_key(), "Content-Type": f"multipart/form-data; boundary={boundary}",
        "User-Agent": "eeter-sdr/1.0 (+https://eeter.prolaps.eu)", "Accept": "application/json"})
    with urllib.request.urlopen(req, timeout=300) as r:
        return json.load(r)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("audio"); ap.add_argument("--lang", default="et"); ap.add_argument("--diarize", action="store_true")
    ap.add_argument("--out")
    a = ap.parse_args()
    try:
        res = transcribe(a.audio, a.lang, a.diarize)
    except urllib.error.HTTPError as e:
        sys.exit(f"HTTP {e.code}: {e.read()[:500].decode(errors='ignore')}")
    Path(a.audio).with_suffix(".jutusta.json").write_text(json.dumps(res, ensure_ascii=False, indent=1), encoding="utf-8")
    text = res.get("text", "")
    print(f"[{res.get('language_code', '?')}] {text}")
    if a.out:
        Path(a.out).write_text(text, encoding="utf-8")


if __name__ == "__main__":
    main()
