import json
import os
from pathlib import Path
from collections import defaultdict

def analyze_structures(root_dir):
    p = Path(root_dir)
    files = list(p.rglob("iframe_network.json"))
    
    fight_keys = set()
    fight_t_keys = set()
    fight_ct_keys = set()
    
    file_categories = defaultdict(set)
    
    for filepath in files:
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                data = json.load(f)
        except:
            continue
            
        if not isinstance(data, list):
            continue
            
        has_round = False
        has_leetify = False
        
        for entry in data:
            url = entry.get('url', '')
            body = entry.get('body')
            
            if "api/match/round/" in url:
                has_round = True
            if "api/match/leetify_rating/" in url:
                has_leetify = True
                
            # Check for fight structures in data/match
            if "api/data/match/" in url and isinstance(body, dict):
                main_data = body.get('data', {})
                if isinstance(main_data, dict):
                    # Check group_N -> items -> fight/fight_t/fight_ct
                    for k, v in main_data.items():
                        if k.startswith('group_') and isinstance(v, list):
                            for player in v:
                                if isinstance(player, dict):
                                    if 'fight' in player and isinstance(player['fight'], dict):
                                        fight_keys.update(player['fight'].keys())
                                    if 'fight_t' in player and isinstance(player['fight_t'], dict):
                                        fight_t_keys.update(player['fight_t'].keys())
                                    if 'fight_ct' in player and isinstance(player['fight_ct'], dict):
                                        fight_ct_keys.update(player['fight_ct'].keys())

        if has_round:
            file_categories['round_only'].add(str(filepath))
        if has_leetify:
            file_categories['leetify_only'].add(str(filepath))
        if has_round and has_leetify:
            file_categories['both'].add(str(filepath))

    print("Structure Analysis Results:")
    print("-" * 30)
    print(f"Files with Round API: {len(file_categories['round_only'])}")
    print(f"Files with Leetify API: {len(file_categories['leetify_only'])}")
    print(f"Files with BOTH: {len(file_categories['both'])}")
    
    # Calculate intersections for files
    round_files = file_categories['round_only']
    leetify_files = file_categories['leetify_only']
    intersection = round_files.intersection(leetify_files) # This should be same as 'both' logic above if set correctly, but let's be explicit
    # Actually my logic above adds to sets independently.
    
    only_round = round_files - leetify_files
    only_leetify = leetify_files - round_files
    both = round_files.intersection(leetify_files)
    
    print(f"Files with ONLY Round: {len(only_round)}")
    print(f"Files with ONLY Leetify: {len(only_leetify)}")
    print(f"Files with BOTH: {len(both)}")
    
    print("\nFight Structure Analysis:")
    print("-" * 30)
    print(f"Fight keys count: {len(fight_keys)}")
    print(f"Fight_T keys count: {len(fight_t_keys)}")
    print(f"Fight_CT keys count: {len(fight_ct_keys)}")
    
    all_keys = fight_keys | fight_t_keys | fight_ct_keys
    
    missing_in_fight = all_keys - fight_keys
    missing_in_t = all_keys - fight_t_keys
    missing_in_ct = all_keys - fight_ct_keys
    
    if not missing_in_fight and not missing_in_t and not missing_in_ct:
        print("PERFECT MATCH: fight, fight_t, and fight_ct have identical keys.")
    else:
        if missing_in_fight: print(f"Keys missing in 'fight': {missing_in_fight}")
        if missing_in_t: print(f"Keys missing in 'fight_t': {missing_in_t}")
        if missing_in_ct: print(f"Keys missing in 'fight_ct': {missing_in_ct}")

if __name__ == "__main__":
    analyze_structures("output_arena")
