#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AutoPOE2 - Character Data Structured Snapshotter & Evolution Tracker
=====================================================================
Trích xuất và lưu trữ trạng thái nhân vật theo cấu trúc dữ liệu chuẩn (JSON & Markdown)
kèm timestamp chính xác, giúp AI Agent nắm bắt trọn vẹn quá trình nâng cấp, tiến hóa nhân vật
như một game thủ chuyên nghiệp.

Tài liệu tham chiếu:
- character_target/current_state.md
- character_target/build_endgame_plan.md
- poe2_production_Config.ini
"""

import os
import sys
import json
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Dict, Any, Optional, List

if sys.platform == "win32":
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
        sys.stderr.reconfigure(encoding="utf-8", errors="replace")
    except Exception:
        pass

WORKSPACE_ROOT = Path(__file__).resolve().parent.parent
CHARACTER_TARGET_DIR = WORKSPACE_ROOT / "character_target"
SNAPSHOTS_DIR = CHARACTER_TARGET_DIR / "snapshots"
EVOLUTION_MD = CHARACTER_TARGET_DIR / "CHARACTER_EVOLUTION.md"
CURRENT_STATE_MD = CHARACTER_TARGET_DIR / "current_state.md"
POE2_CONFIG_PATH = Path(r"C:\Users\Admin\OneDrive\Documents\My Games\Path of Exile 2\poe2_production_Config.ini")


def get_current_timestamps() -> tuple[str, str]:
    """Trả về (ISO 8601 Local with offset, ISO 8601 UTC)"""
    now_local = datetime.now().astimezone()
    now_utc = datetime.now(timezone.utc)
    return now_local.isoformat(), now_utc.strftime("%Y-%m-%dT%H:%M:%SZ")


def build_character_snapshot(
    character_name: str = "BEONGUSI",
    level: int = 90,
    class_name: str = "Monk",
    ascendancy: str = "Martial Artist",
    league: str = "Forbidden Rites",
    cur_es: int = 4713,
    max_es: int = 4713,
    cur_ward: int = 240,
    cur_mana: int = 876,
    combo_builder_gem: str = "MonkTempestFlurry",
    finisher_gem: str = "MonkTempestBell"
) -> Dict[str, Any]:
    """Tạo đối tượng snapshot dữ liệu nhân vật có cấu trúc chuẩn mực."""
    iso_local, iso_utc = get_current_timestamps()

    snapshot: Dict[str, Any] = {
        "schema_version": "autopoe2.character_snapshot/v1",
        "timestamp_local": iso_local,
        "timestamp_utc": iso_utc,
        "character": {
            "name": character_name,
            "account": f"{character_name}#3653",
            "class": class_name,
            "ascendancy": ascendancy,
            "level": level,
            "league": league,
            "defense_type": "Chaos Inoculation (CI)",
            "life_invariant": "HP 1/1 (Chaos Immune)",
            "client_build_target": "6AA2213C"
        },
        "vitals": {
            "life_current": 1,
            "life_max": 1,
            "energy_shield_current": cur_es,
            "energy_shield_max": max_es,
            "energy_shield_in_combat_target": 5500,
            "ward_current": cur_ward,
            "ward_max": cur_ward,
            "mana_current": cur_mana,
            "mana_max": cur_mana,
            "spirit_available": 7,
            "spirit_reserved": 140,
            "spirit_max": 147
        },
        "skill_loadout": {
            "slot_Q": {
                "key": "Q",
                "vk_code": "0x51",
                "role": "COMBO_BUILDER",
                "role_vi": "Chiêu Tích Combo Liên Hoàn",
                "current_gem": combo_builder_gem,
                "previous_gem": "IceStrike",
                "target_combo_points": 4,
                "description": "Đòn đánh tốc độ cao tích lũy từ 1 đến 4 điểm Combo Points để chuẩn bị kích nổ Chuông Bão."
            },
            "slot_R": {
                "key": "R",
                "vk_code": "0x52",
                "role": "COMBO_FINISHER",
                "role_vi": "Chiêu Kích Nổ / Kết Liễu Diện Rộng",
                "current_gem": finisher_gem,
                "prerequisite": "BẮT BUỘC ĐỦ 4 COMBO POINTS TỪ PHÍM Q HOẶC BOSS STAGGER >= 80%",
                "description": "Cắm Chuông Bão xuống tâm điểm Boss / quái Rare để kích nổ sóng xung kích Lôi Điện cực đại."
            },
            "slot_RMB": {
                "key": "mouse_right",
                "vk_code": "VK_RBUTTON",
                "role": "SUSTAINED_AOE_BUFF",
                "role_vi": "Chiêu Xoay Bão Lôi / Duy Trì Buff",
                "current_gem": "MonkChargedStaff",
                "buff_duration_sec": 40,
                "description": "Tích tụ lôi năng và xoay bão quanh thân gậy, duy trì sát thương AoE liên tục và sạc thanh Swirling Spiral."
            },
            "slot_MMB": {
                "key": "mouse_middle",
                "vk_code": "VK_MBUTTON",
                "role": "GAP_CLOSER_DEBUFF",
                "role_vi": "Chiêu Áp Sát & Yểm Bùa Suy Yếu",
                "current_gem": "DruidWolfLeapAttack",
                "description": "Hóa Sói nhảy áp sát từ xa và cast bùa chú (Mark/Debuff) khiến Boss nhận thêm lượng lớn sát thương."
            },
            "slot_T": {
                "key": "T",
                "vk_code": "0x54",
                "role": "PRE_BUFF_INITIATION",
                "role_vi": "Chiêu Tăng Nộ Trước Giao Tranh",
                "current_gem": "DruidBearWarcry",
                "rage_granted": 30,
                "description": "Gầm Bear Warcry lấy tức thì 30 Rage trước khi giao chiến quái Rare / Boss."
            },
            "slot_LMB": {
                "key": "mouse_left",
                "vk_code": "VK_LBUTTON",
                "role": "PRIMARY_CLEAR",
                "role_vi": "Chiêu Dọn Quái Cơ Bản",
                "current_gem": "MartialArtistMantraofIllusionsSkill",
                "description": "Phóng ảo ảnh phân thân dọn quái nhỏ, duy trì di chuyển linh hoạt không tốn mana."
            },
            "slot_SPACE": {
                "key": "space",
                "vk_code": "VK_SPACE",
                "role": "MOBILITY_IFRAME",
                "role_vi": "Chiêu Lăn Né Bất Tử (Iframe)",
                "current_gem": "DodgeRoll",
                "trigger_condition": "Nguy cơ nhận đòn chí mạng hoặc ES < 70%",
                "description": "Hủy animation đòn đánh lập tức, lùi về cự ly an toàn để ES tự sạc lại."
            },
            "slot_F": {
                "key": "F",
                "vk_code": "0x46",
                "role": "SKILL_8",
                "role_vi": "Kỹ Năng Thứ 8 Của Người Chơi",
                "current_gem": "BoundSkill8",
                "note": "TUYỆT ĐỐI CẤM GỬI PHÍM F ĐỂ TƯƠNG TÁC THẾ GIỚI (INV-KEY-NO-F-FOR-INTERACT)"
            }
        },
        "keystones_and_ascendancy": [
            {
                "name": "Chaos Inoculation (CI)",
                "effect": "Maximum Life becomes 1, Immune to Chaos Damage"
            },
            {
                "name": "Hollow Form Technique",
                "effect": "Clones Whirling Assault from Hollow Focus / Power Charges"
            },
            {
                "name": "Runic Meridians",
                "effect": "Enhanced elemental conversion & staff resonance"
            },
            {
                "name": "Way of the Stonefist",
                "effect": "Transforms gloves (Lochtonial Caress) to refund Power/Frenzy/Endurance charges"
            }
        ],
        "equipped_weapon": {
            "name": "Wrath Branch, Sinister Quarterstaff",
            "type": "Quarterstaff",
            "stat_focus": "Increased Attack Speed, Lightning Damage, Energy Shield per Charge"
        },
        "evolution_context": {
            "progression_stage": "ENDGAME_T16_MAPPING",
            "recent_upgrade_note": "Chuyển đổi Chiêu Tích Combo (Q) từ Ice Strike sang Tempest Flurry giúp tăng tốc độ tích 4 điểm Combo Points để kích nổ Chuông Bão (R)."
        }
    }
    return snapshot


def save_snapshot(snapshot: Dict[str, Any]) -> Path:
    """Lưu snapshot vào thư mục snapshots/ kèm timestamp định dạng file."""
    SNAPSHOTS_DIR.mkdir(parents=True, exist_ok=True)
    ts_compact = datetime.now().strftime("%Y%m%d_%H%M%S")
    char_name = snapshot["character"]["name"]
    filename = f"char_{char_name}_{ts_compact}.json"
    filepath = SNAPSHOTS_DIR / filename

    with open(filepath, "w", encoding="utf-8") as f:
        json.dump(snapshot, f, indent=2, ensure_ascii=False)

    print(f"[Snapshotter] >> Đã lưu snapshot dữ liệu nhân vật: {filepath}", flush=True)
    return filepath


def update_evolution_journal(snapshot: Dict[str, Any]) -> None:
    """Ghi nhật ký tiến hóa nhân vật vào CHARACTER_EVOLUTION.md."""
    ts_str = snapshot["timestamp_local"]
    char = snapshot["character"]
    vitals = snapshot["vitals"]
    skills = snapshot["skill_loadout"]
    weapon = snapshot["equipped_weapon"]

    entry = f"""
### [MỐC TIẾN HÓA: {ts_str}] — Level {char['level']} {char['ascendancy']} ({char['defense_type']})
- **Nhân vật**: `{char['name']}` | **League**: `{char['league']}`
- **Hồ Sinh Tồn**: ES `{vitals['energy_shield_current']}/{vitals['energy_shield_max']}` | Ward `{vitals['ward_current']}` | Mana `{vitals['mana_current']}` | Life `{vitals['life_current']}/{vitals['life_max']}` (CI 100% Chaos Immune)
- **Vũ khí**: `{weapon['name']}`
- **Bảng Ánh Xạ Vai Trò Kỹ Năng (Skill Roles)**:
  - **[Q] COMBO_BUILDER**: `{skills['slot_Q']['current_gem']}` *(trước: `{skills['slot_Q'].get('previous_gem', 'N/A')}`)* $\\rightarrow$ Tích lũy 1–4 Combo Points.
  - **[R] COMBO_FINISHER**: `{skills['slot_R']['current_gem']}` $\\rightarrow$ Cắm Chuông Bão Lôi diện rộng khi đủ 4 điểm combo.
  - **[RMB] SUSTAINED_BUFF**: `{skills['slot_RMB']['current_gem']}` $\\rightarrow$ Duy trì buff xoay bão 40s.
  - **[MMB] GAP_CLOSER**: `{skills['slot_MMB']['current_gem']}` $\\rightarrow$ Hóa Sói nhảy áp sát & gán bùa debuff.
  - **[T] PRE_BUFF**: `{skills['slot_T']['current_gem']}` $\\rightarrow$ Gầm Warcry lấy 30 Rage.
  - **[LMB] CLEAR**: `{skills['slot_LMB']['current_gem']}` $\\rightarrow$ Dọn quái nhỏ không tốn tài nguyên.
  - **[Space] IFRAME**: `{skills['slot_SPACE']['current_gem']}` $\\rightarrow$ Dodge Roll hủy animation thoát hiểm.
- **Ghi chú nâng cấp**: {snapshot['evolution_context']['recent_upgrade_note']}
---
"""

    if not EVOLUTION_MD.exists():
        header = """# NHẬT KÝ TIẾN HÓA & NÂNG CẤP NHÂN VẬT (CHARACTER EVOLUTION JOURNAL)
> Tài liệu cấu trúc lưu vết trọn vẹn hành trình tiến hóa nhân vật từ Leveling đến Endgame T16.
> Mỗi mốc nâng cấp (Gems, Gear, Passives, Vitals) được AI Agent ghi nhận và học hỏi như một Pro Player.

---
"""
        content = header + entry
    else:
        with open(EVOLUTION_MD, "r", encoding="utf-8") as f:
            old_content = f.read()
        # Chèn mốc mới lên đầu phần nhật ký
        if "---" in old_content:
            parts = old_content.split("---", 1)
            content = parts[0] + "---\n" + entry + parts[1].lstrip("\n-")
        else:
            content = old_content + "\n" + entry

    with open(EVOLUTION_MD, "w", encoding="utf-8") as f:
        f.write(content)

    print(f"[Snapshotter] >> Đã cập nhật Nhật Ký Tiến Hóa: {EVOLUTION_MD}", flush=True)


def main():
    print("=========================================================")
    print("   AutoPOE2 - Character Data Structured Snapshotter      ")
    print("=========================================================")

    # Khởi tạo snapshot với dữ liệu thực tế mới nhất
    snapshot = build_character_snapshot(
        character_name="BEONGUSI",
        level=90,
        class_name="Monk",
        ascendancy="Martial Artist",
        league="Forbidden Rites",
        cur_es=4713,
        max_es=4713,
        cur_ward=240,
        cur_mana=876,
        combo_builder_gem="MonkTempestFlurry",  # Nâng cấp mới của người dùng
        finisher_gem="MonkTempestBell"
    )

    # 1. Lưu file JSON cấu trúc máy đọc
    saved_path = save_snapshot(snapshot)

    # 2. Cập nhật nhật ký tiến hóa Markdown
    update_evolution_journal(snapshot)

    print("[Snapshotter] ✅ Hoàn tất snapshot dữ liệu nhân vật thành công!")
    return 0


if __name__ == "__main__":
    sys.exit(main())
