"""v2.3 개선사항 검증 스크립트"""
import json
from pathlib import Path

# 최신 출력 디렉토리 찾기
result_base = Path(__file__).parent.parent.parent / "분석결과"
v2_dirs = sorted([d for d in result_base.iterdir() if d.is_dir() and d.name.endswith('_v2')],
                 key=lambda d: d.stat().st_mtime)
latest_dir = v2_dirs[-1]

print(f"검증 디렉토리: {latest_dir.name}\n")

# validated_data.json 로드
with open(latest_dir / 'validated_data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

print("=" * 70)
print("v2.3 개선사항 검증")
print("=" * 70)

# 1. 우르드/리옌 평타 effectiveAttackTime 검증
print("\n[1] 우르드/리옌 평타 effectiveAttackTime (Projectile TriggerTime)")
print("-" * 70)

for stalker_id in ['urud', 'lian']:
    stalker = data.get(stalker_id, {})
    basic_attacks = stalker.get('basicAttacks', {})

    for weapon_type, attacks in basic_attacks.items():
        for attack in attacks:
            montage_name = attack['montageName']
            actual_duration = attack['actualDuration']
            effective_time = attack.get('effectiveAttackTime', actual_duration)
            projectile_triggers = attack.get('projectileTriggerTimes', [])

            if projectile_triggers:
                saved_time = actual_duration - effective_time
                print(f"{stalker_id}/{weapon_type} 평타:")
                print(f"  Montage: {montage_name}")
                print(f"  ActualDuration: {actual_duration:.2f}초")
                print(f"  EffectiveAttackTime: {effective_time:.2f}초")
                print(f"  ProjectileTriggers: {projectile_triggers}")
                print(f"  => {saved_time:.2f}초 빠름!")

# 2. 공격 스킬 판정 검증
print("\n[2] 공격 스킬 판정 (SimpleSendEvent Event Tag)")
print("-" * 70)

test_skills = {
    'SK130301': '바란 일격분쇄 (Event.SkillActivate)',
    'SK150201': '클라드 다시 흙으로 (Event.SkillActivate)',
    'SK190201': '리옌 연화 (Event.SpawnProjectile)',
    'SK190101': '리옌 정조준 (ProjectileShot)',
}

for skill_id, expected_desc in test_skills.items():
    found = False
    for stalker_id, stalker in data.items():
        all_skills = (stalker.get('defaultSkills', []) +
                     [stalker.get('subSkill')] +
                     [stalker.get('ultimateSkill')])

        for skill in all_skills:
            if skill and skill.get('skillId') == skill_id:
                is_attack = len(skill.get('montageData', [])) > 0 and skill['montageData'][0].get('hasAttack', False)
                status = "공격 스킬" if is_attack else "유틸리티"
                print(f"{skill_id}: {skill.get('name')} => {status}")
                print(f"  Expected: {expected_desc}")

                # 몽타주 데이터 확인
                if skill.get('montageData'):
                    montage = skill['montageData'][0]
                    attack_notifies = montage.get('attackNotifies', [])
                    print(f"  AttackNotifies: {len(attack_notifies)}개")

                    # SimpleSendEvent 확인
                    for notify in attack_notifies:
                        if 'SimpleSendEvent' in notify.get('notifyClass', ''):
                            event_tag = notify.get('customProperties', {}).get('Event Tag', '')
                            print(f"    - SimpleSendEvent: {event_tag}")

                found = True
                break
        if found:
            break

    if not found:
        print(f"{skill_id}: NOT FOUND")

# 3. 유틸리티 스킬 확인 (공격 노티파이 없음)
print("\n[3] 유틸리티 스킬 (공격 노티파이 없음)")
print("-" * 70)

utility_skills = {
    'SK110207': '우르드 Reload',
    'SK190209': '리옌 재장전'
}

for skill_id, expected_name in utility_skills.items():
    found = False
    for stalker_id, stalker in data.items():
        all_skills = (stalker.get('defaultSkills', []) +
                     [stalker.get('subSkill')] +
                     [stalker.get('ultimateSkill')])

        for skill in all_skills:
            if skill and skill.get('skillId') == skill_id:
                has_attack = len(skill.get('montageData', [])) > 0 and skill['montageData'][0].get('hasAttack', False)
                status = "공격" if has_attack else "유틸리티"
                print(f"{skill_id}: {skill.get('name')} => {status}")

                if skill.get('montageData'):
                    montage = skill['montageData'][0]
                    attack_notifies_count = len(montage.get('attackNotifies', []))
                    print(f"  AttackNotifies: {attack_notifies_count}개")

                found = True
                break
        if found:
            break

# 4. 레네 소환체 섹션 확인
print("\n[4] 레네 소환체 섹션")
print("-" * 70)

rene = data.get('rene', {})
summons = rene.get('summons', {})

if summons:
    print(f"레네 소환체: {len(summons)}개")
    for summon_name, summon_data in summons.items():
        print(f"\n  {summon_name}:")
        print(f"    SummonSkillId: {summon_data.get('summonSkillId')}")
        print(f"    SummonSkillName: {summon_data.get('summonSkillName')}")
        print(f"    SkillDamageRate: {summon_data.get('skillDamageRate')}")
        print(f"    AttackInterval: {summon_data.get('attackInterval')}초")
        print(f"    DotType: {summon_data.get('dotType', 'None')}")
else:
    print("레네 소환체 데이터 없음!")

print("\n" + "=" * 70)
print("검증 완료!")
print("=" * 70)
