#!/usr/bin/env python3
"""
Final ASR Verification with OpenAI Whisper
Word-level timestamps and comprehensive analysis
"""

import os
import sys
import re
from openai import OpenAI

# Check API key
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
if not OPENAI_API_KEY:
    print("❌ OPENAI_API_KEY not set!")
    sys.exit(1)

client = OpenAI(api_key=OPENAI_API_KEY)

# Original test text
TEST_TEXT = """<excited> In the heart of an enchanted kingdom, where magic flowed like rivers and mythical beasts roamed freely, there lived a legendary warrior princess named Aisha. </excited> She was known throughout the land for her incredible courage, her mastery of ancient combat arts, and her ability to communicate with all living creatures.

<whisper> But few knew of the prophecy that surrounded her birth. </whisper> The ancient seers had foretold that she would one day face the greatest darkness the world had ever seen, and only she possessed the power to defeat it.

Aisha spent her childhood training in the sacred mountains with the wise monks. <curious> They taught her not just the physical arts of combat, but also the spiritual disciplines that would strengthen her mind and soul. </curious> Every dawn, she would practice her sword techniques as the sun rose over the peaks. Every evening, she would meditate under the stars, learning to harness the cosmic energies that flowed through all things.

<angry> One fateful day, dark clouds gathered over the kingdom! </angry> The evil demon lord Ravaksh had awakened from his thousand-year slumber. His army of shadow warriors began to sweep across the land, corrupting everything they touched. Villages were destroyed, forests withered, and despair spread like wildfire.

<sigh> The kingdom's armies fought valiantly, but they were no match for Ravaksh's dark magic. </sigh> One by one, the greatest warriors fell. The king's advisors urged him to flee, to abandon the kingdom and save what few lives they could.

<excited> But Aisha refused to give up! </excited> She knew this was the moment the prophecy had spoken of. She gathered the remaining defenders and devised a daring plan. They would launch a surprise attack on Ravaksh's fortress while he was still consolidating his power.

एक बार की बात है, ऐशा ने अपने सबसे भरोसेमंद योद्धाओं को इकट्ठा किया। उन्होंने एक खतरनाक योजना बनाई। वे रावक्ष के किले पर हमला करेंगे। यह असंभव लग रहा था, लेकिन उनके पास कोई विकल्प नहीं था। राज्य का भविष्य उनके हाथों में था।

<whisper> Under the cover of darkness, they approached the fortress. </whisper> The shadow guards patrolled the walls, their red eyes glowing in the night. <laugh> But Aisha had learned from the wind spirits how to move unseen! </laugh> She led her team through secret passages known only to the ancient monks.

The infiltration was successful. They reached the inner sanctum where Ravaksh was performing a dark ritual. <angry> He was trying to summon an even greater evil from the void! </angry> There was no time to waste.

<excited> Aisha drew her legendary sword, which began to glow with divine light! </excited> The blade had been forged by the celestial smiths themselves, imbued with the power to vanquish any darkness. As she charged forward, her companions engaged the shadow warriors, giving her a clear path to Ravaksh.

The battle that followed was epic. <curious> Ravaksh wielded powers that defied comprehension - he could bend reality itself, create illusions that seemed more real than reality, and summon storms of pure destruction. </curious> But Aisha had trained for this her entire life.

She dodged his dark bolts, deflected his curse spells, and pressed forward relentlessly. <whisper> She remembered the words of her master: "True strength comes not from power, but from purpose." </whisper> Her purpose was clear - protect her people, save her kingdom, restore the light.

With a mighty cry, she leaped high into the air, her sword blazing like a star. <excited> The blade struck true, piercing through Ravaksh's dark armor and into his corrupted heart! </excited> The demon lord let out a terrible scream as the divine light consumed him.

<laugh> The shadow army dissolved like smoke in the wind! </laugh> The dark clouds parted, and sunlight flooded the land once more. The corrupted forests began to heal, flowers bloomed, and the rivers ran clear again.

<excited> Aisha returned to her kingdom as a hero beyond measure! </excited> The people celebrated for seven days and seven nights. Songs were written about her bravery, statues were erected in her honor, and her legend would be told for a thousand generations.

<whisper> But Aisha remained humble. </whisper> She knew that true victory was not in defeating enemies, but in protecting those she loved. <sigh> She had seen too much loss, too much suffering. </sigh> From that day forward, she dedicated herself to teaching the next generation, ensuring they would be ready when darkness threatened again.

<excited> And so the kingdom prospered under her watchful protection, and peace reigned for many years to come! </excited>"""

AUDIO_FILE = "fixed_test.wav"

def clean_text(text):
    """Remove emotion tags."""
    return re.sub(r'<[^>]+>', '', text).strip()

def extract_words(text):
    """Get word list."""
    return [w.lower() for w in re.findall(r'\b[\w]+\b', text)]

print("="*80)
print("🔬 FINAL ASR VERIFICATION")
print("="*80)
print()

# File info
file_size = os.path.getsize(AUDIO_FILE)
duration_est = (file_size - 44) / (24000 * 2)

print(f"📁 Audio: {AUDIO_FILE} ({file_size/1024/1024:.1f} MB, ~{duration_est/60:.1f} min)")
print()

# Reference text
clean_ref = clean_text(TEST_TEXT)
ref_words = extract_words(clean_ref)

print(f"📝 Reference: {len(TEST_TEXT)} chars, {len(ref_words)} words")
print()

# Transcribe
print(f"🎧 Transcribing with OpenAI Whisper...")

with open(AUDIO_FILE, 'rb') as f:
    transcription = client.audio.transcriptions.create(
        model="whisper-1",
        file=f,
        response_format="verbose_json"
    )

print(f"✅ Done!")
print()

# Analysis
transcript_text = transcription.text
trans_words = extract_words(transcript_text)

print(f"📊 Results:")
print(f"   Transcribed: {len(trans_words)} words")
print(f"   Accuracy: {len(trans_words)/len(ref_words)*100:.1f}%")
print()

# Find missing
trans_set = set(trans_words)
ref_set = set(ref_words)
missing_unique = ref_set - trans_set
missing_count = sum(1 for w in ref_words if w not in trans_set)

print(f"   Missing: {missing_count} words ({len(missing_unique)} unique)")
print()

# Check ending
print(f"🎯 Ending Analysis:")
last_10_ref = ref_words[-10:]
last_10_found = sum(1 for w in last_10_ref if w in trans_set)
print(f"   Last 10 reference words: {last_10_found}/10 found")
print(f"   Reference ending: ...{' '.join(last_10_ref)}")

if transcription.words:
    last_trans = transcription.words[-1]
    print(f"   Last transcribed: '{last_trans.word}' at {last_trans.end:.1f}s")
    print()

# Critical check
CRITICAL_PHRASES = [
    "next generation",
    "ensuring",
    "darkness threatened",
    "kingdom prospered",
    "watchful protection",
    "peace reigned",
    "many years"
]

print(f"🔍 Critical Ending Phrases:")
transcript_lower = transcript_text.lower()
for phrase in CRITICAL_PHRASES:
    found = phrase in transcript_lower
    status = "✅" if found else "❌"
    print(f"   {status} '{phrase}'")
print()

# Save report
with open("final_asr_report.txt", 'w') as f:
    f.write("FINAL ASR VERIFICATION REPORT\n")
    f.write("="*80 + "\n\n")
    f.write(f"Audio: {AUDIO_FILE}\n")
    f.write(f"Duration: {duration_est:.1f}s\n")
    f.write(f"Reference words: {len(ref_words)}\n")
    f.write(f"Transcribed words: {len(trans_words)}\n")
    f.write(f"Accuracy: {len(trans_words)/len(ref_words)*100:.1f}%\n")
    f.write(f"Missing: {missing_count}\n\n")
    
    f.write("CRITICAL PHRASES:\n")
    for phrase in CRITICAL_PHRASES:
        found = "YES" if phrase in transcript_lower else "NO"
        f.write(f"  {phrase}: {found}\n")
    f.write("\n")
    
    f.write("FULL TRANSCRIPT:\n")
    f.write("-"*80 + "\n")
    f.write(transcript_text + "\n\n")
    
    if transcription.words:
        f.write("TIMESTAMPS:\n")
        f.write("-"*80 + "\n")
        for w in transcription.words[-50:]:  # Last 50 words
            f.write(f"{w.start:.1f}s-{w.end:.1f}s: {w.word}\n")

print(f"📄 Report saved: final_asr_report.txt")
print()

# Verdict
print("="*80)
print("📊 VERDICT")
print("="*80)
print()

critical_found = sum(1 for p in CRITICAL_PHRASES if p in transcript_lower)
accuracy = len(trans_words)/len(ref_words)*100

if critical_found >= 6 and accuracy >= 90:
    print("✅ FIX IS WORKING! Audio contains full ending.")
    print(f"   Critical phrases: {critical_found}/7 found")
    print(f"   Overall accuracy: {accuracy:.1f}%")
elif critical_found >= 4:
    print("⚠️  PARTIAL SUCCESS - Most ending present but some missing")
    print(f"   Critical phrases: {critical_found}/7 found")
elif critical_found <= 2:
    print("❌ FIX NOT WORKING - Ending still truncated")
    print(f"   Critical phrases: {critical_found}/7 found")
    print(f"   Still missing from end!")
else:
    print("❓ UNCLEAR - Some improvements but issues remain")
    print(f"   Critical phrases: {critical_found}/7 found")

print()

