import sqlite3
import pandas as pd
import json
import os
import sys

# Add parent directory
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from web.config import Config

def check_mapping():
    conn = sqlite3.connect(Config.DB_L2_PATH)
    
    # Join economy and teams via match_id
    # We need to match steam_id (in eco) to group_uids (in teams)
    
    # 1. Get Economy R1 samples
    query_eco = """
    SELECT match_id, steam_id_64, side 
    FROM fact_round_player_economy 
    WHERE round_num = 1
    LIMIT 10
    """
    eco_rows = pd.read_sql_query(query_eco, conn)
    
    if eco_rows.empty:
        print("No Economy R1 data found.")
        conn.close()
        return

    print("Checking Mapping...")
    for _, row in eco_rows.iterrows():
        mid = row['match_id']
        sid = row['steam_id_64']
        side = row['side']
        
        # Get Teams for this match
        query_teams = "SELECT group_id, group_fh_role, group_uids FROM fact_match_teams WHERE match_id = ?"
        team_rows = pd.read_sql_query(query_teams, conn, params=(mid,))
        
        for _, t_row in team_rows.iterrows():
            # Check if sid is in group_uids (which contains UIDs, not SteamIDs!)
            # We need to map SteamID -> UID
            # Use dim_players or fact_match_players
            q_uid = "SELECT uid FROM fact_match_players WHERE match_id = ? AND steam_id_64 = ?"
            uid_res = conn.execute(q_uid, (mid, sid)).fetchone()
            if not uid_res:
                continue
            
            uid = str(uid_res[0])
            group_uids = str(t_row['group_uids']).split(',')
            
            if uid in group_uids:
                role = t_row['group_fh_role']
                print(f"Match {mid}: Steam {sid} (UID {uid}) is on Side {side} in R1.")
                print(f"  Found in Group {t_row['group_id']} with FH Role {role}.")
                print(f"  MAPPING: Role {role} = {side}")
                break
                
    conn.close()

if __name__ == "__main__":
    check_mapping()
