"""AutoPOE2 - Atlas Progression Planner CLI Tool (Doc 56 / Doc 65 / Doc 70).
=============================================================================
Công cụ dòng lệnh điều phối tiến trình mở khóa và thăng tiến cây bản đồ Endgame Atlas:
- Quản trị chiến lược thăng tiến 115+ nodes cho nhân vật Monk CI Level 1-100.
- Khóa chặt bất biến INV-ATLAS-FARM-NODE (tuyệt đối cấm The Burning Monolith / Arbiter of Ash).
- Ưu tiên các map mở, an toàn Tier 15 (Deserted, Fortress, Mineshaft, Creek, Marsh, Dunes).
- Hỗ trợ mô phỏng tiến trình cày map liên tục và phân bổ điểm Cây Nội Tại theo DAG.

Tuân thủ nghiêm ngặt:
- Rule 1: Cold Path Tier 2 (Python 3.11).
- Rule 4: Module hóa, tệp tinh gọn < 150 dòng, ủy nhiệm toàn bộ nghiệp vụ cho src/assistant_tool/atlas/.
- Rule 5: Empirical Definition of Done & [MÔ PHỎNG THUẬT TOÁN HEADLESS - KHÔNG PHẢI LIVE GAME].
"""

import argparse
import sys
from pathlib import Path
from typing import Any, Dict, Optional

try:
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(encoding="utf-8")
except Exception:
    pass

# Thêm root workspace vào sys.path để import đồng bộ
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from src.assistant_tool.atlas.graph import AtlasGraph, calculate_node_weight
from src.assistant_tool.atlas.progression_planner import (
    AtlasProgressionPlanner,
    ProgressionDecision,
    ProgressionStrategy,
)
from src.assistant_tool.atlas.progression_service import AtlasProgressionService
from src.assistant_tool.atlas_knowledge_base import AtlasKnowledgeBase


def print_completion_stats(graph: AtlasGraph) -> None:
    """In bảng thống kê tiến trình hoàn thành Atlas."""
    stats = graph.get_completion_stats()
    print("=" * 60)
    print("📊 [TIẾN TRÌNH ATLAS POE2 v0.5.5+ ENDGAME GRAPH]")
    print("=" * 60)
    print(f"  • Tổng số Node trên cây:        {stats['total_nodes']}")
    print(f"  • Đã hoàn thành (Completed):    {stats['completed_count']} ({stats['completion_rate']}%)")
    print(f"  • Đạt mốc thưởng (Bonus):      {stats['bonus_completed_count']} ({stats['bonus_completion_rate']}%)")
    print(f"  • Node tiếp giáp biên (Frontier): {stats['frontier_count']}")
    print(f"  • Điểm Nội Tại tích lũy:       {stats['total_atlas_passive_points']} Points")
    print("=" * 60)


def plan_next_step(
    planner: AtlasProgressionPlanner,
    current_node_id: Optional[str] = None,
    tier_cap: int = 16,
) -> Optional[ProgressionDecision]:
    """Hoạch định bước đi tiếp theo trên đồ thị Atlas."""
    decision = planner.select_next_node(current_node_id=current_node_id, current_tier_cap=tier_cap)
    if not decision:
        print("⚠️ Không tìm thấy Node kế tiếp hợp lệ trong giới hạn Tier cap.")
        return None

    # Khóa chặt bất biến INV-ATLAS-FARM-NODE
    if AtlasKnowledgeBase.is_forbidden_for_waystone_farming(decision.target_node.name):
        raise RuntimeError(
            f"VI PHẠM BẤT BIẾN INV-ATLAS-FARM-NODE: Node '{decision.target_node.name}' bị cấm tuyệt đối!"
        )

    weight = calculate_node_weight(decision.target_node)
    print(f"🎯 [BƯỚC ĐI TIẾP THEO] -> Node: '{decision.target_node.name}' (Tier {decision.target_node.tier}, Weight: {weight})")
    print(f"   • Chiến lược:     {decision.strategy.value}")
    print(f"   • Node bước kế:   '{decision.next_step_node.name}' (ID: {decision.next_step_node.node_id})")
    print(f"   • Lộ trình qua:   {' -> '.join(decision.route_node_ids)}")
    print(f"   • Lý do lựa chọn: {decision.reason}")
    if decision.recommended_tablets:
        print(f"   • Tablet gợi ý:   {', '.join(decision.recommended_tablets)}")
    return decision


def simulate_multi_map(
    service: AtlasProgressionService,
    num_maps: int = 5,
    tier_cap: int = 16,
) -> None:
    """Mô phỏng chuỗi cày map liên tục và phân bổ điểm Cây Nội Tại (Rule 5 Headless Simulation)."""
    print(f"\n🚀 Khởi chạy mô phỏng {num_maps} maps liên tiếp [MÔ PHỎNG THUẬT TOÁN HEADLESS - KHÔNG PHẢI LIVE GAME]:")
    planner = AtlasProgressionPlanner(graph=service.atlas_graph)

    for i in range(num_maps):
        decision = planner.select_next_node(current_tier_cap=tier_cap)
        if not decision:
            print(f"⚠️ Hết node khả dụng ở map thứ {i+1}!")
            break

        target = decision.target_node
        res = service.on_map_completed(
            node_id=target.node_id,
            bonus_completed=True,
            wallet={"Chaos Orb": 20 + i * 15, "Exalted Orb": i // 2},
            current_gold=1500 * (i + 1),
        )
        alloc_name = res.newly_allocated_passive.name if res.newly_allocated_passive else "None"
        print(
            f"  [Map {i+1:02d}] '{target.name}' (T{target.tier}) -> "
            f"+1 Atlas Point | Passive: {alloc_name} | "
            f"Net Worth: {res.current_net_worth_chaos:.1f}C (Delta: +{res.delta_net_worth_chaos:.1f}C)"
        )

    print_completion_stats(service.atlas_graph)


def main() -> None:
    parser = argparse.ArgumentParser(description="AutoPOE2 Atlas Progression Planner CLI Tool")
    parser.add_argument(
        "--strategy",
        choices=["FULL_COMPLETION_RUSH", "BONUS_POINTS_RUSH", "CITADEL_PINNACLE_RUSH", "SPECIAL_ENCOUNTER_FARM"],
        default="FULL_COMPLETION_RUSH",
        help="Chiến lược điều phối đồ thị Atlas",
    )
    parser.add_argument("--tier-cap", type=int, default=16, help="Cấp độ Tier tối đa")
    parser.add_argument("--simulate-maps", type=int, default=0, help="Số map mô phỏng cày liên tiếp")
    parser.add_argument("--stats", action="store_true", help="Hiển thị thống kê tiến trình")
    args = parser.parse_args()

    service = AtlasProgressionService()
    strategy = ProgressionStrategy(args.strategy)
    planner = AtlasProgressionPlanner(graph=service.atlas_graph, strategy=strategy)

    if args.stats or (not args.simulate_maps and len(sys.argv) == 1):
        print_completion_stats(service.atlas_graph)

    if args.simulate_maps > 0:
        simulate_multi_map(service, num_maps=args.simulate_maps, tier_cap=args.tier_cap)
    else:
        plan_next_step(planner, tier_cap=args.tier_cap)


if __name__ == "__main__":
    main()
