#!/usr/bin/env python3
"""
Activation Order Group 추출 스크립트

Blueprint.json에서 스토커별 스킬의 ActivationOrderGroup 값을 추출합니다.

사용법:
    python extract_activation_order_groups.py <Blueprint.json 경로>
"""

import json
import sys
from pathlib import Path
from collections import defaultdict


def extract_activation_order_groups(json_path):
    """Blueprint.json에서 ActivationOrderGroup 추출"""

    with open(json_path, 'r', encoding='utf-8') as f:
        blueprints = json.load(f)

    # 스토커별 스킬 그룹화
    stalker_skills = defaultdict(list)

    stalkers = ['Hilda', 'Urud', 'Nave', 'Baran', 'Rio', 'Clad', 'Rene', 'Sinobu', 'Lian', 'Cazimord']

    for bp in blueprints:
        asset_name = bp.get('AssetName', '')

        # GA_Skill_{Stalker}_ 패턴 찾기
        if asset_name.startswith('GA_Skill_'):
            for stalker in stalkers:
                if f'_{stalker}_' in asset_name:
                    # ActivationOrderGroup 찾기
                    activation_order = None
                    for var in bp.get('Variables', []):
                        if var.get('Name') == 'ActivationOrderGroup':
                            activation_order = var.get('DefaultValue', '0')
                            break

                    skill_name = asset_name.replace(f'GA_Skill_{stalker}_', '')

                    stalker_skills[stalker].append({
                        'skill': skill_name,
                        'order_group': int(activation_order) if activation_order else 0,
                        'full_name': asset_name
                    })

    return stalker_skills


def print_stalker_skills(stalker_skills):
    """스토커별 스킬과 ActivationOrderGroup 출력"""

    print("\n스토커별 Activation Order Group")
    print("=" * 100)

    for stalker, skills in sorted(stalker_skills.items()):
        print(f"\n{stalker}:")

        # Order Group별로 정렬
        skills_by_group = defaultdict(list)
        for skill in skills:
            skills_by_group[skill['order_group']].append(skill['skill'])

        for group in sorted(skills_by_group.keys(), reverse=True):
            print(f"  Group {group}: {', '.join(sorted(skills_by_group[group]))}")


def print_statistics(stalker_skills):
    """통계 정보 출력"""

    print("\n\n통계")
    print("=" * 100)

    # 각 Group별 사용 빈도
    group_count = defaultdict(int)
    for stalker, skills in stalker_skills.items():
        for skill in skills:
            group_count[skill['order_group']] += 1

    print("\nGroup별 스킬 수:")
    for group in sorted(group_count.keys(), reverse=True):
        print(f"  Group {group}: {group_count[group]}개")

    # 스토커별 스킬 수
    print("\n스토커별 스킬 수:")
    for stalker, skills in sorted(stalker_skills.items(), key=lambda x: len(x[1]), reverse=True):
        print(f"  {stalker}: {len(skills)}개")


def main():
    if len(sys.argv) < 2:
        print("사용법: python extract_activation_order_groups.py <Blueprint.json 경로>")
        sys.exit(1)

    json_path = Path(sys.argv[1])

    if not json_path.exists():
        print(f"오류: 파일을 찾을 수 없습니다: {json_path}")
        sys.exit(1)

    print(f"분석 중: {json_path}")

    stalker_skills = extract_activation_order_groups(json_path)

    print(f"\n총 {sum(len(skills) for skills in stalker_skills.values())}개의 스킬 발견")

    print_stalker_skills(stalker_skills)
    print_statistics(stalker_skills)


if __name__ == "__main__":
    main()
