
import sqlite3
import pandas as pd
import os

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

def analyze_team_dmg_per_1k():
    if not os.path.exists(L3_DB_PATH):
        print(f"Error: L3 DB not found at {L3_DB_PATH}")
        return

    conn_l3 = sqlite3.connect(L3_DB_PATH)
    conn_l2 = sqlite3.connect(L2_DB_PATH)
    
    print("--- Analysis: Team Dmg/$1k (Economy Efficiency) ---")
    
    try:
        # 1. Get all L3 features
        query = """
        SELECT f.steam_id_64, f.eco_avg_damage_per_1k, p.username
        FROM dm_player_features f
        LEFT JOIN dim_players p ON f.steam_id_64 = p.steam_id_64
        ORDER BY f.eco_avg_damage_per_1k DESC
        """
        
        # Attach L2 for username lookup
        # We can't attach across connections easily in sqlite python without ATTACH DATABASE command
        # So let's fetch L3 first, then map names from L2
        
        df_l3 = pd.read_sql_query("SELECT steam_id_64, eco_avg_damage_per_1k FROM dm_player_features", conn_l3)
        
        if df_l3.empty:
            print("No data in L3 Features.")
            return

        # Fetch names
        ids = tuple(df_l3['steam_id_64'].tolist())
        placeholders = ','.join(['?'] * len(ids))
        q_names = f"SELECT steam_id_64, username FROM dim_players WHERE steam_id_64 IN ({placeholders})"
        df_names = pd.read_sql_query(q_names, conn_l2, params=ids)
        
        # Merge
        df = df_l3.merge(df_names, on='steam_id_64', how='left')
        
        # Sort
        df = df.sort_values('eco_avg_damage_per_1k', ascending=False)
        
        print(f"{'Rank':<5} {'Player':<20} {'Dmg/$1k':<10}")
        print("-" * 40)
        
        for idx, row in df.iterrows():
            rank = idx + 1 # This index is not rank if we iterated row by row after sort, wait.
            # reset_index to get rank
            pass
        
        df = df.reset_index(drop=True)
        for idx, row in df.iterrows():
            name = row['username'] if row['username'] else row['steam_id_64']
            val = row['eco_avg_damage_per_1k']
            print(f"#{idx+1:<4} {name:<20} {val:.2f}")
            
    except Exception as e:
        print(f"Error: {e}")
        import traceback
        traceback.print_exc()
    finally:
        conn_l2.close()
        conn_l3.close()

if __name__ == "__main__":
    analyze_team_dmg_per_1k()
