import os
import subprocess
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()
API_KEY = os.getenv("NVIDIA_API_KEY")

test_text = "This is a quick test to see if we can get exact word timestamps from the whisper model."
audio_file = "test_audio.wav"

def test_riva_tts():
    print("\n🎙️ 1. Teste NVIDIA Magpie Multilingual (Stimme: Aria) via Riva...")
    
    # Der genaue Befehl aus der NVIDIA Dokumentation
    command = [
        "python3", "python-clients/scripts/tts/talk.py",
        "--server", "grpc.nvcf.nvidia.com:443",
        "--use-ssl",
        "--metadata", "function-id", "877104f7-e885-42b9-8de8-f6e4c6303969",
        "--metadata", "authorization", f"Bearer {API_KEY}",
        "--language-code", "en-US",
        "--text", test_text,
        "--voice", "Magpie-Multilingual.EN-US.Aria",
        "--output", audio_file
    ]
    
    try:
        result = subprocess.run(command, capture_output=True, text=True)
        
        if os.path.exists(audio_file) and os.path.getsize(audio_file) > 0:
            print(f"✅ Audio erfolgreich generiert: {audio_file}")
            return True
        else:
            print("❌ Fehler bei der Audio-Generierung.")
            print("Terminal Output:", result.stderr)
            return False
    except Exception as e:
        print(f"❌ Ausführungsfehler: {e}")
        return False

def test_asr():
    print("\n👂 2. Teste OpenAI Whisper-large-v3 (Word Timestamps)...")
    
    client = OpenAI(
        base_url="https://integrate.api.nvidia.com/v1",
        api_key=API_KEY
    )
    
    try:
        with open(audio_file, "rb") as audio:
            transcription = client.audio.transcriptions.create(
                model="openai/whisper-large-v3",
                file=audio,
                response_format="verbose_json",
                timestamp_granularities=["word"]
            )
        
        print("✅ Transkription erfolgreich! Prüfe Word-Timestamps:\n")
        
        if hasattr(transcription, 'words') and transcription.words:
            for word_info in transcription.words[:5]:
                print(f"Wort: '{word_info.word}' | Start: {word_info.start}s | Ende: {word_info.end}s")
            print("\n🎉 ERFOLG! Wir haben die perfekten Daten für den Hormozi-Schnitt!")
        else:
            print("⚠️ FEHLSCHLAG: Whisper hat den Text erkannt, liefert aber KEINE Wort-für-Wort Zeitstempel zurück.")
            print(f"Erkannter Text: {transcription.text}")
            
    except Exception as e:
        print(f"❌ ASR Fehler: {e}")

if __name__ == "__main__":
    if test_riva_tts():
        test_asr()
