#!/usr/bin/env python3
"""
Debug script to test database connection and see what's actually happening.
"""

import sys
import os

# Add the src directory to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

from api.database import MusicBrainzDatabase
from api.api_client import MusicBrainzAPIClient

def test_connections():
    """Test both database and API connections."""
    print("🧪 Debugging MusicBrainz Connections")
    print("=" * 50)
    
    # Test database connection
    print("\n1. Testing Database Connection...")
    db = MusicBrainzDatabase()
    db_connected = db.connect()
    print(f"Database connection result: {db_connected}")
    
    if db_connected:
        # Test a simple query
        try:
            cursor = db.cursor
            cursor.execute("SELECT COUNT(*) as count FROM artist")
            count = cursor.fetchone()['count']
            print(f"✅ Database query successful: {count:,} artists found")
        except Exception as e:
            print(f"❌ Database query failed: {e}")
        finally:
            db.disconnect()
    
    # Test API connection
    print("\n2. Testing API Connection...")
    api = MusicBrainzAPIClient()
    api_connected = api.test_connection()
    print(f"API connection result: {api_connected}")
    
    # Test cleaner initialization
    print("\n3. Testing Cleaner Initialization...")
    from cli.main import MusicBrainzCleaner
    
    cleaner = MusicBrainzCleaner(use_database=True)
    print(f"Cleaner use_database flag: {cleaner.use_database}")
    print(f"Cleaner has db attribute: {hasattr(cleaner, 'db')}")
    print(f"Cleaner has api attribute: {hasattr(cleaner, 'api')}")
    
    if hasattr(cleaner, 'db') and cleaner.db:
        print(f"Database connection status: {cleaner.db.connection is not None}")
    
    return db_connected, api_connected

if __name__ == "__main__":
    db_ok, api_ok = test_connections()
    
    print(f"\n📊 Summary:")
    print(f"Database connection: {'✅ OK' if db_ok else '❌ FAILED'}")
    print(f"API connection: {'✅ OK' if api_ok else '❌ FAILED'}")
    
    if not db_ok and not api_ok:
        print("\n❌ Both connections failed!")
        sys.exit(1)
    elif not db_ok:
        print("\n⚠️  Database failed, but API is available")
    else:
        print("\n✅ Database connection is working!") 