
import sqlite3
import pandas as pd
import os

# Config
L2_DB_PATH = r'database/L2/L2_Main.sqlite'

def debug_player_data(username_pattern='jAckY'):
    if not os.path.exists(L2_DB_PATH):
        print(f"Error: L2 DB not found at {L2_DB_PATH}")
        return

    conn_l2 = sqlite3.connect(L2_DB_PATH)
    
    print(f"--- Debugging Player: {username_pattern} ---")
    
    try:
        # 1. Find the player ID
        q_id = f"SELECT steam_id_64, username FROM dim_players WHERE username LIKE '%{username_pattern}%'"
        df_player = pd.read_sql_query(q_id, conn_l2)
        
        if df_player.empty:
            print("Player not found.")
            return
            
        target_id = df_player.iloc[0]['steam_id_64']
        name = df_player.iloc[0]['username']
        print(f"Found: {name} ({target_id})")
        
        # 2. Check Match Stats (ADR, Rounds)
        q_matches = f"""
        SELECT match_id, round_total, adr, (adr * round_total) as damage_calc
        FROM fact_match_players 
        WHERE steam_id_64 = '{target_id}'
        """
        df_matches = pd.read_sql_query(q_matches, conn_l2)
        
        total_dmg = df_matches['damage_calc'].sum()
        total_rounds = df_matches['round_total'].sum()
        print(f"\nMatch Stats:")
        print(f"Matches Played: {len(df_matches)}")
        print(f"Total Rounds: {total_rounds}")
        print(f"Total Damage (Calc): {total_dmg:,.0f}")
        
        # 3. Check Economy Stats (Spend)
        q_eco = f"""
        SELECT match_id, COUNT(*) as rounds_with_eco, SUM(equipment_value) as spend
        FROM fact_round_player_economy
        WHERE steam_id_64 = '{target_id}'
        GROUP BY match_id
        """
        df_eco = pd.read_sql_query(q_eco, conn_l2)
        
        total_spend = df_eco['spend'].sum()
        total_eco_rounds = df_eco['rounds_with_eco'].sum()
        
        print(f"\nEconomy Stats:")
        print(f"Matches with Eco Data: {len(df_eco)}")
        print(f"Rounds with Eco Data: {total_eco_rounds}")
        print(f"Total Spend: ${total_spend:,.0f}")
        
        # 4. Compare
        print(f"\nComparison:")
        print(f"Rounds in Match Stats: {total_rounds}")
        print(f"Rounds in Eco Stats:   {total_eco_rounds}")
        
        if total_eco_rounds < total_rounds:
            print(f"⚠️ WARNING: Missing economy data for {total_rounds - total_eco_rounds} rounds!")
            
            # Find matches with missing eco data
            merged = df_matches.merge(df_eco, on='match_id', how='left')
            missing = merged[merged['spend'].isna() | (merged['spend'] == 0)]
            
            if not missing.empty:
                print(f"\nMatches with ZERO spend/Missing Eco:")
                print(missing[['match_id', 'round_total', 'damage_calc']])
                
                # Check calculation impact
                valid_dmg = merged[merged['spend'] > 0]['damage_calc'].sum()
                print(f"\nRecalculation ignoring missing matches:")
                print(f"Valid Damage: {valid_dmg:,.0f}")
                print(f"Total Spend: ${total_spend:,.0f}")
                if total_spend > 0:
                    new_val = valid_dmg / (total_spend / 1000)
                    print(f"Corrected Dmg/$1k: {new_val:.2f}")
                
    except Exception as e:
        print(f"Error: {e}")
    finally:
        conn_l2.close()

if __name__ == "__main__":
    debug_player_data()
