import sqlite3
import os

# Define database paths
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
L2_PATH = os.path.join(BASE_DIR, 'database', 'L2', 'L2_Main.sqlite')

def check_l2_tables():
    print(f"Checking L2 database at: {L2_PATH}")
    if not os.path.exists(L2_PATH):
        print("Error: L2 database not found!")
        return

    conn = sqlite3.connect(L2_PATH)
    cursor = conn.cursor()
    
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
    tables = cursor.fetchall()
    print("Tables in L2 Database:")
    for table in tables:
        print(f" - {table[0]}")
        
    conn.close()

def debug_player_query(player_name_query=None):
    print(f"\nDebugging Player Query (L2)...")
    conn = sqlite3.connect(L2_PATH)
    cursor = conn.cursor()
    
    try:
        # Check if 'dim_players' exists
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='dim_players';")
        if not cursor.fetchone():
            print("Error: 'dim_players' table not found!")
            return

        # Check schema of dim_players
        print("\nChecking dim_players schema:")
        cursor.execute("PRAGMA table_info(dim_players)")
        for col in cursor.fetchall():
            print(col)

        # Check sample data
        print("\nSampling dim_players (first 5):")
        cursor.execute("SELECT * FROM dim_players LIMIT 5")
        for row in cursor.fetchall():
            print(row)
            
        # Test Search
        search_term = 'zy'
        print(f"\nTesting search for '{search_term}':")
        cursor.execute("SELECT * FROM dim_players WHERE name LIKE ?", (f'%{search_term}%',))
        results = cursor.fetchall()
        print(f"Found {len(results)} matches.")
        for r in results:
            print(r)

    except Exception as e:
        print(f"Error querying L2: {e}")
    finally:
        conn.close()

if __name__ == '__main__':
    check_l2_tables()
    debug_player_query()
