import json
import os
import sys

# Thêm root dự án vào sys.path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))

from server.world.martial_catalog import create_standard_active_skills
from server.world.skill_tag_catalog import get_canonical_skill_tags

def export_to_TS():
    tags = get_canonical_skill_tags()
    skills = create_standard_active_skills()
    
    # 1. Export Tags
    tags_TS_obj = {}
    for tag_key, tag_def in tags.items():
        tags_TS_obj[tag_def.tag.value] = {
            "id": tag_def.tag.value,
            "category": tag_def.category.value,
            "name_vi": tag_def.name_vi,
            "name_en": tag_def.name_en,
            "description": tag_def.description,
            "affected_modifiers": tag_def.affected_modifiers
        }
        
    tags_TS_content = f"""/**
 * Tự động tạo từ server/world/skill_tag_catalog.py
 * CHÚ Ý: KHÔNG SỬA TRỰC TIẾP FILE NÀY.
 */
export const SKILL_TAGS = {json.dumps(tags_TS_obj, indent=2, ensure_ascii=False)};

export function getTagById(id: any) {{
  return (SKILL_TAGS as any)[id] || null;
}}

if (typeof window !== 'undefined') {{
  (window as any).SkillTags = {{
    SKILL_TAGS,
    getTagById,
  }};
}}
"""

    tags_path = os.path.join("client", "cocos", "assets", "scripts", "data", "skill_tags.ts")
    with open(tags_path, "w", encoding="utf-8") as f:
        f.write(tags_TS_content)
        
    # 2. Export Skills
    # Do skill_catalog.TS hiện tại có các field dành riêng cho frontend như icon, vfxPreset, telegraphType, rangeMeters
    # Ta sẽ đọc file skill_catalog.TS cũ, lấy các trường đó, trộn với tags từ backend
    
    import re
    skill_catalog_path = os.path.join("client", "cocos", "assets", "scripts", "data", "skill_catalog.ts")
    
    with open(skill_catalog_path, "r", encoding="utf-8") as f:
        old_content = f.read()
        
    # Cập nhật bằng regex hoặc eval TS
    # Cách tốt hơn: ghi thẳng dữ liệu kết hợp
    skills_TS_obj = {}
    
    # Mapping Frontend-specific visual data
    visual_data = {
        1000: {"icon": "⚔️", "vfxPreset": "FIRE", "telegraphType": None, "rangeMeters": 2.5, "aoeRadiusMeters": 1.5, "energyCost": 0, "cooldownSec": 0.25, "castTimeSec": 0.15, "weaponArchetype": "SLASH"},
        1001: {"icon": "⚡", "vfxPreset": "THUNDER", "telegraphType": "line", "rangeMeters": 14.0, "aoeRadiusMeters": 2.0},
        1002: {"icon": "🗡️", "vfxPreset": "THUNDER", "telegraphType": "cone", "rangeMeters": 8.0, "aoeRadiusMeters": 3.5},
        1003: {"icon": "🪡", "vfxPreset": "POISON", "telegraphType": "line", "rangeMeters": 10.0, "aoeRadiusMeters": 1.8},
        1004: {"icon": "☣️", "vfxPreset": "POISON", "telegraphType": "circle", "rangeMeters": 6.0, "aoeRadiusMeters": 5.0},
        1005: {"icon": "❄️", "vfxPreset": "FROST", "telegraphType": "circle", "rangeMeters": 7.0, "aoeRadiusMeters": 6.0},
        1006: {"icon": "🏹", "vfxPreset": "FROST", "telegraphType": "line", "rangeMeters": 16.0, "aoeRadiusMeters": 2.2},
        1007: {"icon": "🌪️", "vfxPreset": "FIRE", "telegraphType": "circle", "rangeMeters": 3.5, "aoeRadiusMeters": 3.0},
        1008: {"icon": "🔥", "vfxPreset": "FIRE", "telegraphType": "cone", "rangeMeters": 4.5, "aoeRadiusMeters": 2.5},
        1009: {"icon": "🔨", "vfxPreset": "EARTH", "telegraphType": "circle", "rangeMeters": 6.0, "aoeRadiusMeters": 5.0},
        1010: {"icon": "🛡️", "vfxPreset": "EARTH", "telegraphType": None, "rangeMeters": 0.0, "aoeRadiusMeters": 3.0},
        1011: {"icon": "🩸", "vfxPreset": "POISON", "telegraphType": "circle", "rangeMeters": 8.0, "aoeRadiusMeters": 4.5},
        1012: {"icon": "💀", "vfxPreset": "EARTH", "telegraphType": "circle", "rangeMeters": 5.0, "aoeRadiusMeters": 3.0},
        1099: {"icon": "💨", "vfxPreset": "THUNDER", "telegraphType": None, "rangeMeters": 4.5, "aoeRadiusMeters": 1.0}
    }
    
    # 1000 and 1099 are not in backend catalog usually (basic attack, dodge), so add them manually
    skills_TS_obj[1000] = {
        "id": 1000, "key": "primary_strike", "name": "Thường Quy Trảm Kích", "element": "fire", "icon": "⚔️",
        "energyCost": 0, "cooldownSec": 0.25, "castTimeSec": 0.15, "weaponArchetype": "SLASH", "vfxPreset": "FIRE",
        "telegraphType": None, "rangeMeters": 2.5, "aoeRadiusMeters": 1.5, "desc": "Đòn vung vũ khí cơ bản có nhịp điệu, giải phóng kình lực chém ngang.",
        "tags": ["attack", "melee", "physical"]
    }
    
    for s_id, s in skills.items():
        v = visual_data.get(s_id, {})
        skills_TS_obj[s_id] = {
            "id": s.skill_id,
            "key": s.skill_name.lower().replace(" ", "_").replace("ấ", "a").replace("ệ", "e").replace("ị", "i").replace("ổ", "o"), # simple mock, better to keep old keys
            "name": s.skill_name,
            "element": s.element.value,
            "icon": v.get("icon", "✨"),
            "energyCost": s.energy_cost,
            "cooldownSec": s.cooldown_ms / 1000.0,
            "castTimeSec": s.cast_time_ms / 1000.0,
            "weaponArchetype": v.get("weaponArchetype", "ANY"),
            "vfxPreset": v.get("vfxPreset", "FIRE"),
            "telegraphType": v.get("telegraphType", "circle"),
            "rangeMeters": v.get("rangeMeters", 5.0),
            "aoeRadiusMeters": v.get("aoeRadiusMeters", s.base_aoe_radius if hasattr(s, "base_aoe_radius") else 2.0),
            "desc": s.upside_desc,
            "tags": [t.value for t in s.tags]
        }
        
        # fix hardcoded keys and elements
        key_map = {
            1001: "cuu_tieu_loi_kiem", 1002: "thanh_phong_van_kiem_vu", 1003: "u_minh_huyet_doc_cham",
            1004: "thien_ma_boc_doc_kinh", 1005: "bang_phach_han_quang_tran", 1006: "bang_tien_xuyen_tam",
            1007: "liet_hoa_toan_phong_tram", 1008: "liet_diem_boc_khi_tram", 1009: "kim_cang_truy_dia_chan",
            1010: "kim_cang_bat_hoai_the", 1011: "huyet_ma_khap_huyet_kinh", 1012: "man_cot_trieu_hon_do"
        }
        elem_map = {
            "KIM": "thunder", "MOC": "poison", "THUY": "frost", "HOA": "fire", "THO": "earth"
        }
        if s_id in key_map:
            skills_TS_obj[s_id]["key"] = key_map[s_id]
        if s.element.value in elem_map:
            skills_TS_obj[s_id]["element"] = elem_map[s.element.value]
            
    skills_TS_obj[1099] = {
        "id": 1099, "key": "huyen_anh_bo", "name": "Huyễn Ảnh Bộ", "element": "phantom", "icon": "💨",
        "energyCost": 15, "cooldownSec": 3.0, "castTimeSec": 0.05, "weaponArchetype": "THRUST", "vfxPreset": "THUNDER",
        "telegraphType": None, "rangeMeters": 4.5, "aoeRadiusMeters": 1.0, "desc": "Lướt né tức thì với 250ms khung bất tử (i-frame), để lại tàn ảnh và tích trữ tối đa 3 tích điểm.",
        "tags": ["movement", "defensive", "agility_aligned"]
    }
    
    skills_TS_content = f"""/**
 * FreeExile Canonical Active Skill Catalog
 * Tự động đồng bộ từ Backend để bảo đảm Tag PoE2.
 */

export const CANONICAL_SKILLS = Object.freeze({json.dumps(skills_TS_obj, indent=2, ensure_ascii=False)});

export function getSkillById(id: any) {{
  return (CANONICAL_SKILLS as any)[id] || null;
}}

export function getAllCanonicalSkills() {{
  return Object.values(CANONICAL_SKILLS);
}}

export function getSkillsByElement(elem: any) {{
  if (!elem) return [];
  const normalized = String(elem).toLowerCase();
  return Object.values(CANONICAL_SKILLS).filter(s => s.element.toLowerCase() === normalized);
}}

export function getSkillsByTag(tag: any) {{
  if (!tag) return [];
  const normalized = String(tag).toLowerCase();
  return Object.values(CANONICAL_SKILLS).filter(s => s.tags && s.tags.includes(normalized));
}}

if (typeof window !== 'undefined') {{
  (window as any).SkillCatalog = {{
    CANONICAL_SKILLS,
    getSkillById,
    getAllCanonicalSkills,
    getSkillsByElement,
    getSkillsByTag,
  }};
}}
"""
    
    with open(skill_catalog_path, "w", encoding="utf-8") as f:
        f.write(skills_TS_content)
        
    # 3. Export Support Skills (Dị Biến Tà Ấn)
    from server.world.martial_catalog import create_standard_augment_sigils
    sigils = create_standard_augment_sigils()
    sigils_TS_obj = {}

    for s_id, s in sigils.items():
        sigils_TS_obj[s_id] = {
            'id': s.sigil_id,
            'name': s.sigil_name,
            'augmentType': s.augment_type.value,
            'requiredTags': [t.value for t in s.required_tags],
            'excludedTags': [t.value for t in s.excluded_tags] if hasattr(s, 'excluded_tags') else [],
            'descUpside': s.upside_desc,
            'descDownside': s.downside_desc
        }

    support_content = f"""/**
 * Tự động đồng bộ từ Backend để bảo đảm cơ chế Support Gem của PoE2
 */
export const SUPPORT_SKILLS = {json.dumps(sigils_TS_obj, indent=2, ensure_ascii=False)};

export function getSupportById(id: any) {{
  return (SUPPORT_SKILLS as any)[id] || null;
}}

if (typeof window !== 'undefined') {{
  (window as any).SupportSkillCatalog = {{
    SUPPORT_SKILLS,
    getSupportById,
  }};
}}
"""
    support_path = os.path.join("client", "cocos", "assets", "scripts", "data", "support_skill_catalog.ts")
    with open(support_path, "w", encoding="utf-8") as f:
        f.write(support_content)

    print("Exported SKILL_TAGS, SKILLS, and SUPPORT_SKILLS to TS.")

if __name__ == "__main__":
    export_to_TS()
