#!/usr/bin/env python3
"""
Test the fix for last chunk truncation
Uses same text that showed the bug
"""

import requests
import re

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

# Same text that showed the bug
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>"""

print("="*80)
print("🔧 TESTING FIX FOR LAST CHUNK TRUNCATION")
print("="*80)
print()
print(f"📝 Test text: 4,682 chars (same as before)")
print(f"🐛 Bug: Last chunk was capped at 2000 tokens → truncated")
print(f"✅ Fix: Increased to 50 tokens/char with 20000 cap")
print()

print(f"🎙️  Generating audio with FIXED code...")
print(f"   (This will take ~2 minutes)")
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,  # Global max (not used for chunking)
            "seed": 42,
        },
        timeout=300  # Longer timeout
    )
    
    if response.status_code != 200:
        print(f"❌ API Error: {response.status_code}")
        print(response.text[:500])
        exit(1)
    
    # Save audio
    output_file = "fixed_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 ({duration/60:.2f} minutes)")
    print()
    
    # Compare with buggy version
    print(f"📊 Comparison:")
    print(f"   Before fix: 15,438,732 bytes (321.64s)")
    print(f"   After fix:  {audio_bytes:,} bytes ({duration:.2f}s)")
    
    if audio_bytes > 15_438_732:
        diff = audio_bytes - 15_438_732
        print(f"   Difference: +{diff:,} bytes (+{(audio_bytes/15_438_732-1)*100:.1f}%)")
        print(f"   ✅ LARGER FILE = FIX WORKING!")
    else:
        print(f"   ⚠️  Same or smaller - fix may not have worked")
    print()
    
    # Check headers
    print(f"📊 Response Info:")
    headers = ['X-Text-Chunked', 'X-RTF', 'X-Audio-Seconds']
    for h in headers:
        if h in response.headers:
            print(f"   {h}: {response.headers[h]}")
    print()
    
    print(f"="*80)
    print(f"🎧 VERIFICATION NEEDED:")
    print(f"="*80)
    print()
    print(f"Please listen to the LAST 30 seconds:")
    print(f"   ffplay -ss {int(duration-30)} {output_file}")
    print()
    print(f"Expected ending phrases:")
    print(f"   ✓ 'next generation'")
    print(f"   ✓ 'ensuring they would be ready'")
    print(f"   ✓ 'when darkness threatened'")
    print(f"   ✓ 'kingdom prospered'")
    print(f"   ✓ 'watchful protection'")
    print(f"   ✓ 'peace reigned'")
    print(f"   ✓ 'many years to come'")
    print()
    
except Exception as e:
    print(f"❌ ERROR: {e}")
    import traceback
    traceback.print_exc()

