#!/usr/bin/env python3
"""
Groq Whisper Transcription
Usage: python3 groq-whisper.py <audio_file_path>
Returns: transcribed text on stdout
"""

import sys
import os
import urllib.request
import json

def transcribe(file_path: str) -> str:
    api_key = os.environ.get("GROQ_API_KEY")
    if not api_key:
        env_file = os.path.expanduser("~/aria/.env")
        if os.path.exists(env_file):
            with open(env_file) as f:
                for line in f:
                    if line.startswith("GROQ_API_KEY="):
                        api_key = line.strip().split("=", 1)[1].strip().strip('"').strip("'")
                        break

    if not api_key:
        print("[Groq: kein API Key gefunden]", file=sys.stderr)
        return ""

    url = "https://api.groq.com/openai/v1/audio/transcriptions"

    with open(file_path, "rb") as f:
        audio_data = f.read()

    # Groq rejects .oga (Telegram default for voice). Rename extension to .ogg in form data.
    base = os.path.basename(file_path)
    stem, ext = os.path.splitext(base)
    if ext.lower() in (".oga", ".opus", ""):
        filename = stem + ".ogg"
    else:
        filename = base
    boundary = "----FormBoundary7MA4YWxkTrZu0gW"

    body = (
        f"--{boundary}\r\n"
        f'Content-Disposition: form-data; name="model"\r\n\r\n'
        f"whisper-large-v3-turbo\r\n"
        f"--{boundary}\r\n"
        f'Content-Disposition: form-data; name="language"\r\n\r\n'
        f"de\r\n"
        f"--{boundary}\r\n"
        f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'
        f"Content-Type: audio/ogg\r\n\r\n"
    ).encode("utf-8") + audio_data + f"\r\n--{boundary}--\r\n".encode("utf-8")

    req = urllib.request.Request(
        url,
        data=body,
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": f"multipart/form-data; boundary={boundary}",
            "User-Agent": "aria-voice/1.0 (curl-compatible)",
        },
        method="POST"
    )

    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            result = json.loads(resp.read().decode("utf-8"))
            return result.get("text", "").strip()
    except Exception as e:
        print(f"[Groq Fehler: {e}]", file=sys.stderr)
        return ""

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: groq-whisper.py <audio_file>")
        sys.exit(1)
    text = transcribe(sys.argv[1])
    print(text)
