#!/usr/bin/env python3
"""
Test with the ORIGINAL text that showed the bug
This is the exact text from the user's comprehensive_word_analysis test
"""

import requests
import re

API_KEY = "vn3_cdd6d45f2045d03d5adac56eda6af9a9b781211038972807f35d52dfb6400144"
API_URL = "http://localhost:8000/v1/tts/generate"

# ORIGINAL TEST TEXT that showed the bug
# This is from scripts/detailed_word_analysis.py
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>"""

# The ENDING that should be present (last ~100 chars)
EXPECTED_ENDING = "she dedicated herself to teaching the next generation, ensuring they would be ready when darkness threatened again. And so the kingdom prospered under her watchful protection, and peace reigned for many years to come!"

# Extract last sentence clean text (no emotion tags)
def extract_last_sentence(text):
    """Extract the last sentence without emotion tags."""
    clean = re.sub(r'<[^>]+>', '', text)
    clean = clean.strip()
    # Get last 200 chars
    return clean[-200:]

print("="*80)
print("🔬 ORIGINAL BUG REPRODUCTION TEST")
print("="*80)
print()
print(f"📝 Test Configuration:")
print(f"   Full text length: {len(TEST_TEXT)} chars")
print(f"   Contains emotion tags: {len(re.findall(r'<[^>]+>', TEST_TEXT))} tags")
print(f"   Contains Hindi text: Yes")
print()

last_part = extract_last_sentence(TEST_TEXT)
print(f"📍 Expected ending (last 200 chars, no emotion tags):")
print(f"   '{last_part}'")
print()

# Key phrases that MUST be in the audio
key_ending_phrases = [
    "next generation",
    "ensuring they would be ready",
    "when darkness threatened",
    "kingdom prospered",
    "watchful protection",
    "peace reigned",
    "many years to come"
]

print(f"🎯 Critical phrases that MUST be spoken:")
for phrase in key_ending_phrases:
    print(f"   - '{phrase}'")
print()

print(f"🎙️  Generating audio with ORIGINAL text...")
print(f"   (This will take ~1 minute)")
print()

try:
    response = requests.post(
        API_URL,
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={
            "text": TEST_TEXT,
            "speaker": "lipakshi",
            "temperature": 0.4,
            "top_p": 0.9,
            "max_tokens": 4096,
            "seed": 42,
        },
        timeout=180
    )
    
    if response.status_code != 200:
        print(f"❌ API Error: {response.status_code}")
        print(response.text[:500])
        exit(1)
    
    # Save audio
    output_file = "original_bug_test.wav"
    with open(output_file, 'wb') as f:
        f.write(response.content)
    
    # Analyze
    audio_bytes = len(response.content)
    duration = (audio_bytes - 44) / (24000 * 2)
    
    print(f"✅ Audio generated successfully!")
    print(f"   File: {output_file}")
    print(f"   Size: {audio_bytes:,} bytes")
    print(f"   Duration: {duration:.2f}s")
    print()
    
    # Check headers
    print(f"📊 Response Info:")
    headers = ['X-Text-Chunked', 'X-RTF', 'X-Audio-Seconds', 'X-Request-ID']
    for h in headers:
        if h in response.headers:
            print(f"   {h}: {response.headers[h]}")
    print()
    
    was_chunked = response.headers.get('X-Text-Chunked', 'false') == 'true'
    
    print(f"="*80)
    print(f"🎧 MANUAL VERIFICATION NEEDED")
    print(f"="*80)
    print()
    print(f"The audio file has been generated: {output_file}")
    print(f"Duration: {duration:.2f} seconds")
    print(f"Was chunked: {was_chunked}")
    print()
    print(f"📍 Please listen to the LAST 30 seconds:")
    print(f"   ffplay -ss {int(duration-30)} {output_file}")
    print()
    print(f"🎯 Check if you hear these phrases at the END:")
    for phrase in key_ending_phrases:
        print(f"   ✓ '{phrase}'")
    print()
    print(f"❓ Question: Do you hear ALL of the above phrases?")
    print(f"   If YES: Bug does NOT reproduce (might be fixed or ASR issue)")
    print(f"   If NO: Bug reproduces (last chunk truncation confirmed)")
    print()
    
except Exception as e:
    print(f"❌ ERROR: {e}")
    import traceback
    traceback.print_exc()

