#!/usr/bin/env python3
"""
Simple test for musicbrainz-cleaner database connection.
"""

import psycopg2
import psycopg2.extras
from fuzzywuzzy import fuzz

# Database configuration
DB_HOST = "172.18.0.2"  # Docker container IP that works
DB_PORT = 5432
DB_NAME = "musicbrainz_db"
DB_USER = "musicbrainz"
DB_PASSWORD = "musicbrainz"
DB_CONNECTION_TIMEOUT = 30

def test_database_connection():
    """Test database connection and fuzzy search."""
    print("🧪 Testing MusicBrainz Cleaner Database Connection")
    print("=" * 50)
    
    try:
        # Connect to database
        connection = psycopg2.connect(
            host=DB_HOST,
            port=DB_PORT,
            database=DB_NAME,
            user=DB_USER,
            password=DB_PASSWORD,
            connect_timeout=DB_CONNECTION_TIMEOUT
        )
        
        cursor = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        print("✅ Connected to MusicBrainz database")
        
        # Test basic query
        cursor.execute("SELECT COUNT(*) as count FROM artist")
        count = cursor.fetchone()['count']
        print(f"📊 Found {count:,} artists in database")
        
        # Test artist search
        print("\n🔍 Testing artist search...")
        cursor.execute("SELECT name FROM artist WHERE name = 'The Beatles' LIMIT 1")
        result = cursor.fetchone()
        if result:
            print(f"✅ Found artist: {result['name']}")
            
            # Test recording search
            print("\n🎵 Testing recording search...")
            cursor.execute("""
                SELECT r.name as recording_name, r.gid as recording_mbid
                FROM recording r
                JOIN artist_credit_name acn ON r.artist_credit = acn.artist_credit
                JOIN artist a ON acn.artist = a.id
                WHERE a.name = 'The Beatles' AND r.name ILIKE '%Hey Jude%'
                LIMIT 1
            """)
            recording_result = cursor.fetchone()
            if recording_result:
                print(f"✅ Found recording: {recording_result['recording_name']} (MBID: {recording_result['recording_mbid']})")
            else:
                print("❌ Recording not found")
        else:
            print("❌ Artist not found")
        
        # Test fuzzy search
        print("\n🔍 Testing fuzzy search...")
        test_artist = "ACDC"
        cursor.execute("SELECT name FROM artist LIMIT 1000")
        artists = [row['name'] for row in cursor.fetchall()]
        
        best_match = None
        best_score = 0
        
        for artist in artists:
            score = fuzz.ratio(test_artist.lower(), artist.lower())
            if score > best_score:
                best_score = score
                best_match = artist
        
        if best_score >= 80:
            print(f"✅ Fuzzy match found: {test_artist} → {best_match} (score: {best_score})")
        else:
            print(f"❌ No good fuzzy match found for {test_artist}")
        
        connection.close()
        print("\n✅ MusicBrainz Cleaner database test successful!")
        return True
        
    except Exception as e:
        print(f"❌ Test failed: {e}")
        return False

if __name__ == "__main__":
    import sys
    success = test_database_connection()
    if not success:
        sys.exit(1) 