#!/usr/bin/env python3
"""Transcribe Telegram voice messages via Deepgram API."""
import json, os, requests, sys
from pathlib import Path

HERMES_HOME = Path(os.getenv("HERMES_HOME", Path.home() / ".hermes"))

def load_deepgram_key() -> str:
    key = os.environ.get("DG_KEY", "")
    if key: return key
    cfg = HERMES_HOME / "config.yaml"
    try:
        with open(cfg) as f:
            text = f.read()
        idx = text.find("stt:")
        if idx >= 0:
            section = text[idx:idx+200]
            for line in section.split("\n"):
                if "api_key" in line:
                    return line.split(":", 1)[1].strip().strip('"').strip("'")
    except: pass
    return ""

def load_tg_token() -> str:
    t = os.environ.get("TG_TOKEN", "")
    if t: return t
    env = HERMES_HOME / ".env"
    try:
        with open(env) as f:
            for line in f:
                line = line.strip()
                if line.startswith("TELEGRAM_BOT_TOKEN="):
                    return line.split("=", 1)[1].strip().strip('"').strip("'")
    except: pass
    return ""

def get_file_path(fid: str, tok: str) -> str | None:
    r = requests.get(f"https://api.telegram.org/bot{tok}/getFile", params={"file_id": fid}, timeout=10)
    d = r.json()
    if d.get("ok") and d.get("result", {}).get("file_path"):
        return d["result"]["file_path"]
    return None

def download_audio(p: str, tok: str) -> bytes | None:
    r = requests.get(f"https://api.telegram.org/file/bot{tok}/{p}", timeout=30)
    return r.content if r.status_code == 200 else None

def transcribe(data: bytes, key: str, lang: str = "ru") -> str | None:
    r = requests.post(
        "https://api.deepgram.com/v1/listen",
        headers={"Authorization": f"Token {key}", "Content-Type": "audio/ogg"},
        params={"model": "nova-2", "language": lang, "punctuate": "true"},
        data=data, timeout=60,
    )
    if r.status_code != 200: return None
    try: return r.json()["results"]["channels"][0]["alternatives"][0]["transcript"]
    except: return None

def main():
    if len(sys.argv) < 2:
        print("Usage: transcribe.py <file_id> [--language ru|en]", file=sys.stderr)
        sys.exit(1)
    fid = sys.argv[1]
    lang = sys.argv[sys.argv.index("--language")+1] if "--language" in sys.argv else "ru"
    tok = load_tg_token()
    key = load_deepgram_key()
    if not tok: print("No TG token", file=sys.stderr); sys.exit(1)
    if not key: print("No DG key", file=sys.stderr); sys.exit(1)
    fp = get_file_path(fid, tok)
    if not fp: print("File not found", file=sys.stderr); sys.exit(1)
    audio = download_audio(fp, tok)
    if not audio: print("Download failed", file=sys.stderr); sys.exit(1)
    print(f"Downloaded {len(audio)} bytes...", file=sys.stderr)
    text = transcribe(audio, key, lang)
    if text: print(text)
    else: print("No speech detected", file=sys.stderr); sys.exit(1)

if __name__ == "__main__":
    main()
