import sqlite3
import pandas as pd
import os

L2_PATH = r'd:\Documents\trae_projects\yrtv\database\L2\L2_Main.sqlite'
WEB_PATH = r'd:\Documents\trae_projects\yrtv\database\Web\Web_App.sqlite'

def debug_db():
    # --- L2 Checks ---
    conn = sqlite3.connect(L2_PATH)
    
    print("--- Data Source Type Distribution ---")
    try:
        df = pd.read_sql_query("SELECT data_source_type, COUNT(*) as cnt FROM fact_matches GROUP BY data_source_type", conn)
        print(df)
    except Exception as e:
        print(f"Error: {e}")
        
    print("\n--- Economy Table Count ---")
    try:
        count = conn.execute("SELECT COUNT(*) FROM fact_round_player_economy").fetchone()[0]
        print(f"Rows: {count}")
    except Exception as e:
        print(f"Error: {e}")

    print("\n--- Check util_flash_usage in fact_match_players ---")
    try:
        cursor = conn.cursor()
        cursor.execute("PRAGMA table_info(fact_match_players)")
        cols = [info[1] for info in cursor.fetchall()]
        if 'util_flash_usage' in cols:
            print("Column 'util_flash_usage' EXISTS.")
            nz = conn.execute("SELECT COUNT(*) FROM fact_match_players WHERE util_flash_usage > 0").fetchone()[0]
            print(f"Rows with util_flash_usage > 0: {nz}")
        else:
            print("Column 'util_flash_usage' MISSING.")
    except Exception as e:
        print(f"Error: {e}")

    conn.close()

    # --- Web DB Checks ---
    print("\n--- Web DB Check ---")
    if not os.path.exists(WEB_PATH):
        print(f"Web DB not found at {WEB_PATH}")
        return

    try:
        conn_web = sqlite3.connect(WEB_PATH)
        cursor = conn_web.cursor()
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
        tables = cursor.fetchall()
        print(f"Tables: {[t[0] for t in tables]}")
        
        if 'player_metadata' in [t[0] for t in tables]:
             count = conn_web.execute("SELECT COUNT(*) FROM player_metadata").fetchone()[0]
             print(f"player_metadata rows: {count}")
        conn_web.close()
    except Exception as e:
        print(f"Error checking Web DB: {e}")

if __name__ == "__main__":
    debug_db()
