#!/usr/bin/env python3
"""
궁극기에서 사용하는 GameplayEffect 추출
"""

import json
import sys
from pathlib import Path

STALKERS = ['hilda', 'urud', 'nave', 'baran', 'rio', 'clad', 'rene', 'sinobu', 'lian', 'cazimord']

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

    json_path = Path(sys.argv[1])

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

    assets = data.get('Assets', [])

    # DT_CharacterStat에서 궁극기 ID 추출
    dt_char_stat = next((dt for dt in assets if dt.get('AssetName') == 'DT_CharacterStat'), None)
    stalker_ultimates = {}
    for row in dt_char_stat.get('Rows', []):
        row_name = row['RowName']
        if row_name in STALKERS:
            stalker_ultimates[row_name] = row['Data'].get('ultimateSkill', '')

    # DT_Skill에서 궁극기 gameplayEffectSet 추출
    dt_skill = next((dt for dt in assets if dt.get('AssetName') == 'DT_Skill'), None)

    all_ge_classes = set()
    stalker_ges = {}

    print("=" * 100)
    print("궁극기에서 사용하는 GameplayEffect 목록")
    print("=" * 100)

    for stalker in STALKERS:
        ult_id = stalker_ultimates.get(stalker, '')
        if not ult_id:
            continue

        skill_row = next((row for row in dt_skill['Rows'] if row['RowName'] == ult_id), None)
        if not skill_row:
            continue

        data_field = skill_row['Data']
        effect_set = data_field.get('gameplayEffectSet', [])

        stalker_ges[stalker] = []

        print(f"\n【{stalker.upper()}】 {ult_id} - {data_field.get('name', 'N/A')}")

        if not effect_set:
            print(f"  → gameplayEffectSet 비어있음")
            continue

        for effect in effect_set:
            ge_class = effect.get('gEClass', '')
            trigger = effect.get('trigger', '')
            tag_values = effect.get('gETagValues', [])

            # Ignore 효과는 스킵
            if 'Ignore' in ge_class:
                continue

            # GE 클래스 이름 추출
            if ge_class:
                ge_name = ge_class.split('/')[-1].replace('.', '_').replace('_C', '')
                all_ge_classes.add(ge_class)
                stalker_ges[stalker].append({
                    'name': ge_name,
                    'class': ge_class,
                    'trigger': trigger,
                    'tagValues': tag_values
                })

                print(f"  [{trigger}] {ge_name}")
                if tag_values:
                    for tv in tag_values:
                        tag_name = tv.get('tag', {}).get('tagName', 'Unknown')
                        value = tv.get('value', 0)
                        print(f"    - {tag_name}: {value}")

    print(f"\n\n총 {len(all_ge_classes)}개의 고유한 GE 클래스 발견")
    print("\nGE 클래스 목록:")
    for ge in sorted(all_ge_classes):
        ge_name = ge.split('/')[-1].replace('.', '_').replace('_C', '')
        print(f"  - {ge_name}")

    # JSON 파일로 저장
    output_file = Path(sys.argv[1]).parent / "ultimate_ge_list.json"
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump({
            'stalker_ges': stalker_ges,
            'all_ge_classes': list(all_ge_classes)
        }, f, ensure_ascii=False, indent=2)

    print(f"\n\n결과 저장: {output_file}")

if __name__ == "__main__":
    main()
