#!/usr/bin/env python3
"""
Test script for 100 random songs
Simple single-threaded approach
"""

import sys
import json
import time
from pathlib import Path

# Add the src directory to the path
sys.path.insert(0, '/app')
from src.cli.main import MusicBrainzCleaner

def main():
    print('🚀 Starting test with 100 random songs...')
    
    # Load songs
    input_file = Path('data/songs.json')
    if not input_file.exists():
        print('❌ songs.json not found')
        return
    
    with open(input_file, 'r') as f:
        all_songs = json.load(f)
    
    print(f'📊 Total songs available: {len(all_songs):,}')
    
    # Take 100 random songs
    import random
    sample_songs = random.sample(all_songs, 100)
    print(f'🎯 Testing 100 random songs...')
    
    # Initialize cleaner
    cleaner = MusicBrainzCleaner()
    
    # Process songs
    found_artists = 0
    found_recordings = 0
    failed_songs = []
    
    start_time = time.time()
    
    for i, song in enumerate(sample_songs, 1):
        print(f'  [{i:3d}/100] Processing: "{song.get("artist", "Unknown")}" - "{song.get("title", "Unknown")}"')
        
        try:
            result = cleaner.clean_song(song)
            
            # Extract the cleaned song from the tuple (song_dict, success_boolean)
            cleaned_song, success = result
            
            artist_found = 'mbid' in cleaned_song
            recording_found = 'recording_mbid' in cleaned_song
            
            if artist_found and recording_found:
                found_artists += 1
                found_recordings += 1
                print(f'      ✅ Found both artist and recording')
            else:
                failed_songs.append({
                    'original': song,
                    'cleaned': cleaned_song,
                    'success': success,
                    'artist_found': artist_found,
                    'recording_found': recording_found,
                    'artist_name': song.get('artist', 'Unknown'),
                    'title': song.get('title', 'Unknown')
                })
                print(f'      ❌ Artist: {artist_found}, Recording: {recording_found}')
                
        except Exception as e:
            print(f'      💥 Error: {e}')
            failed_songs.append({
                'original': song,
                'cleaned': {'error': str(e)},
                'artist_found': False,
                'recording_found': False,
                'artist_name': song.get('artist', 'Unknown'),
                'title': song.get('title', 'Unknown'),
                'error': str(e)
            })
    
    end_time = time.time()
    processing_time = end_time - start_time
    
    # Calculate success rates
    artist_success_rate = found_artists / 100 * 100
    recording_success_rate = found_recordings / 100 * 100
    failed_rate = len(failed_songs) / 100 * 100
    
    print(f'\n📊 Final Results:')
    print(f'  ⏱️  Processing time: {processing_time:.2f} seconds')
    print(f'  🚀 Speed: {100/processing_time:.1f} songs/second')
    print(f'  ✅ Artists found: {found_artists}/100 ({artist_success_rate:.1f}%)')
    print(f'  ✅ Recordings found: {found_recordings}/100 ({recording_success_rate:.1f}%)')
    print(f'  ❌ Failed songs: {len(failed_songs)} ({failed_rate:.1f}%)')
    
    # Save detailed report
    if failed_songs:
        report_file = 'data/test_100_results.json'
        report_data = {
            'test_summary': {
                'total_tested': 100,
                'artists_found': found_artists,
                'recordings_found': found_recordings,
                'failed_count': len(failed_songs),
                'artist_success_rate': artist_success_rate,
                'recording_success_rate': recording_success_rate,
                'processing_time_seconds': processing_time,
                'songs_per_second': 100/processing_time
            },
            'failed_songs': failed_songs
        }
        
        with open(report_file, 'w') as f:
            json.dump(report_data, f, indent=2)
        
        print(f'\n📄 Detailed report saved to: {report_file}')
        
        # Show examples of failed songs
        print(f'\n🔍 Examples of failed songs:')
        for i, failed in enumerate(failed_songs[:10], 1):
            print(f'  [{i}] "{failed["artist_name"]}" - "{failed["title"]}"')
            print(f'      Artist found: {failed["artist_found"]}, Recording found: {failed["recording_found"]}')
            if 'error' in failed:
                print(f'      Error: {failed["error"]}')
    else:
        print('\n🎉 All songs processed successfully!')

if __name__ == '__main__':
    main() 