#!/usr/bin/env python3
"""
Simple performance comparison test
"""
import time
import requests
import subprocess

def test_isolated():
    print("=" * 60)
    print("Testing Soprano ISOLATED (5 runs)")
    print("=" * 60)
    
    text = "This is a comprehensive test of Soprano TTS performance measuring realtime factor and generation speed across multiple runs to establish a reliable baseline."
    
    times = []
    for i in range(5):
        print(f"\nRun {i+1}/5...", end=" ", flush=True)
        start = time.time()
        
        response = requests.get(
            "http://localhost:8765/api/test_soprano_stream",
            params={"text": text},
            stream=True
        )
        
        output = f"/tmp/iso_{i}.wav"
        with open(output, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
        
        elapsed = time.time() - start
        
        # Get duration
        result = subprocess.run(
            ['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
             '-of', 'default=noprint_wrappers=1:nokey=1', output],
            capture_output=True, text=True
        )
        duration = float(result.stdout.strip())
        realtime = duration / elapsed
        times.append((elapsed, duration, realtime))
        
        print(f"Elapsed: {elapsed:.2f}s, Audio: {duration:.2f}s, RT: {realtime:.2f}x")
        time.sleep(0.5)
    
    avg_rt = sum(t[2] for t in times) / len(times)
    print(f"\n✓ Average Realtime: {avg_rt:.2f}x")
    return avg_rt

def test_pipeline():
    print("\n" + "=" * 60)
    print("Testing ASYNC PIPELINE (5 runs)")
    print("=" * 60)
    
    text = "This is a comprehensive test of Soprano TTS performance measuring realtime factor and generation speed across multiple runs to establish a reliable baseline."
    
    times = []
    for i in range(5):
        print(f"\nRun {i+1}/5...", end=" ", flush=True)
        
        # Submit job
        job_resp = requests.post("http://localhost:8765/api/speak", json={"text": text})
        
        # Connect and receive
        start = time.time()
        response = requests.get("http://localhost:8765/api/stream/continuous", stream=True)
        
        output = f"/tmp/pipe_{i}.wav"
        bytes_recv = 0
        with open(output, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
                    bytes_recv += len(chunk)
                    if bytes_recv > 700000:  # ~7s audio
                        break
        
        elapsed = time.time() - start
        response.close()
        
        # Get duration
        result = subprocess.run(
            ['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
             '-of', 'default=noprint_wrappers=1:nokey=1', output],
            capture_output=True, text=True
        )
        duration = float(result.stdout.strip()) if result.stdout.strip() else 0
        realtime = duration / elapsed if elapsed > 0 else 0
        times.append((elapsed, duration, realtime))
        
        print(f"Elapsed: {elapsed:.2f}s, Audio: {duration:.2f}s, RT: {realtime:.2f}x")
        time.sleep(1)
    
    avg_rt = sum(t[2] for t in times) / len(times)
    print(f"\n✓ Average Realtime: {avg_rt:.2f}x")
    return avg_rt

def main():
    print("\nLMDEPLOY BACKEND PERFORMANCE TEST")
    print("=" * 60)
    
    iso_rt = test_isolated()
    pipe_rt = test_pipeline()
    
    print("\n" + "=" * 60)
    print("RESULTS")
    print("=" * 60)
    print(f"Soprano Isolated:  {iso_rt:.2f}x realtime")
    print(f"Async Pipeline:    {pipe_rt:.2f}x realtime")
    
    loss = ((iso_rt - pipe_rt) / iso_rt) * 100
    print(f"Performance Loss:  {loss:.1f}%")
    
    if pipe_rt >= 1.0:
        print(f"\n✓ TARGET ACHIEVED: {pipe_rt:.2f}x >= 1.0x")
    else:
        needed = ((1.0 / pipe_rt) - 1.0) * 100
        print(f"\n✗ Target missed, need {needed:.1f}% improvement")
    
    print("=" * 60)

if __name__ == "__main__":
    main()
