"""Tests for Atlas Progression & Reward Service (Chu Kỳ 6).
======================================================
Kiem thu toan dien:
- Khoi tao AtlasProgressionService voi day du thanh phan (Graph, Planner, NetWorth).
- Xu ly map completion co va khong co bonus.
- Tu dong cap diem Atlas Passive Tree theo DAG prerequisites khi dat bonus.
- Tinh toan tai san rong va delta tang truong giua cac map.
- Mo phong chuoi map va in bao cao tuan thu Rule 5: [MO PHONG THUAT TOAN HEADLESS - KHONG PHAI LIVE GAME].
"""

import pytest
from src.assistant_tool.atlas.graph import (
    AtlasGraph,
    AtlasGraphNode,
    NodeProgressionState,
)
from src.assistant_tool.atlas.atlas_tree_planner import (
    AtlasTreePlanner,
    TreePhase,
)
from src.assistant_tool.currency_exchange.net_worth_estimator import (
    NetWorthEstimator,
)
from src.assistant_tool.atlas.progression_service import (
    AtlasProgressionService,
    MapCompletionRewardResult,
)


class TestAtlasProgressionService:
    def test_service_initialization(self):
        """Kiem tra khoi tao AtlasProgressionService voi dependencies mac dinh."""
        service = AtlasProgressionService()
        assert service.atlas_graph.total_nodes >= 115
        assert service.tree_planner.total_nodes == 115
        assert service.tree_planner.allocated_count == 0
        assert service.total_maps_processed == 0
        assert len(service.history) == 0

    def test_map_completed_without_bonus(self):
        """Kiem tra map hoan thanh nhung khong dat bonus: khong cap diem tree."""
        service = AtlasProgressionService()

        # Lay node bien dau tien (REACHABLE_FRONTIER)
        frontier_nodes = service.atlas_graph.get_frontier_nodes()
        assert len(frontier_nodes) > 0
        target_node = frontier_nodes[0]
        node_id = target_node.node_id

        result = service.on_map_completed(
            node_id=node_id,
            bonus_completed=False,
            wallet={"Chaos Orb": 10},
            current_gold=1000,
        )

        assert result.map_node_id == node_id
        assert result.bonus_completed is False
        assert result.newly_allocated_passive is None
        assert result.total_atlas_passive_points == 0
        assert service.tree_planner.allocated_count == 0
        assert target_node.progression_state == NodeProgressionState.COMPLETED
        assert service.total_maps_processed == 1

    def test_map_completed_with_bonus_allocates_tree_point(self):
        """Kiem tra map hoan thanh dat bonus: tu dong phan bo diem Caye Noi Tai theo DAG."""
        service = AtlasProgressionService()

        frontier_nodes = service.atlas_graph.get_frontier_nodes()
        assert len(frontier_nodes) >= 2
        node_1 = frontier_nodes[0]
        node_2 = frontier_nodes[1]

        result = service.on_map_completed(
            node_id=node_1.node_id,
            bonus_completed=True,
            wallet={"Chaos Orb": 20},
            current_gold=2000,
        )

        assert result.map_node_id == node_1.node_id
        assert result.bonus_completed is True
        assert result.newly_allocated_passive is not None
        assert result.newly_allocated_passive.node_id == "sustain_root"
        assert result.newly_allocated_passive.priority_order == 1
        assert result.total_atlas_passive_points == 1
        assert service.tree_planner.allocated_count == 1
        assert node_1.progression_state == NodeProgressionState.BONUS_COMPLETED

        # Kiem tra diem ke tiep khi hoan thanh map tiep theo
        result_2 = service.on_map_completed(
            node_id=node_2.node_id,
            bonus_completed=True,
            wallet={"Chaos Orb": 30},
            current_gold=3000,
        )
        assert result_2.newly_allocated_passive is not None
        assert result_2.newly_allocated_passive.node_id == "sustain_waystone_1"
        assert result_2.newly_allocated_passive.priority_order == 2
        assert result_2.total_atlas_passive_points == 2


    def test_net_worth_tracking_and_delta(self):
        """Kiem tra co che theo doi gia tri tai san rong va delta tang truong."""
        service = AtlasProgressionService()

        # Map 1: Baseline (10 Chaos, gia tri = 10 C)
        r1 = service.on_map_completed(
            node_id="node_1_1",
            bonus_completed=True,
            wallet={"Chaos Orb": 10},
            current_gold=1500,
        )
        assert r1.current_net_worth_chaos == 10.0
        assert r1.delta_net_worth_chaos == 0.0  # Baseline lan dau

        # Map 2: 25 Chaos + 1 Exalted (12.5C) = 37.5C -> Delta = +27.5C
        r2 = service.on_map_completed(
            node_id="node_2_1",
            bonus_completed=True,
            wallet={"Chaos Orb": 25, "Exalted Orb": 1},
            current_gold=3200,
        )
        assert r2.current_net_worth_chaos == 37.5
        assert r2.delta_net_worth_chaos == 27.5

        # Map 3: Nhat duoc 1 Divine (145C) + 30 Chaos = 175C -> Delta = 175 - 37.5 = +137.5C
        r3 = service.on_map_completed(
            node_id="node_2_2",
            bonus_completed=True,
            wallet={"Chaos Orb": 30, "Divine Orb": 1},
            current_gold=6000,
        )
        assert r3.current_net_worth_chaos == 175.0
        assert r3.delta_net_worth_chaos == 137.5

    def test_multi_map_progression_simulation_and_reporting(self, capsys):
        """
        Mo phong chuoi 5 maps lien tiep voi bao cao chuan Rule 5:
        [MO PHONG THUAT TOAN HEADLESS - KHONG PHAI LIVE GAME]
        """
        service = AtlasProgressionService()

        map_sequence = [
            ("node_1_1", {"Chaos Orb": 15}, 2000),
            ("node_2_1", {"Chaos Orb": 35, "Regal Orb": 5}, 4500),
            ("node_2_2", {"Chaos Orb": 50, "Exalted Orb": 2}, 7200),
            ("node_3_1", {"Chaos Orb": 80, "Divine Orb": 1}, 10500),
            ("node_3_2", {"Chaos Orb": 120, "Divine Orb": 2}, 15000),
        ]

        last_report_str = ""
        for nid, wallet, gold in map_sequence:
            res = service.on_map_completed(
                node_id=nid,
                bonus_completed=True,
                wallet=wallet,
                current_gold=gold,
            )
            last_report_str = service.format_reward_report(res)

        print("\n" + last_report_str)

        # Kiem tra nhan Rule 5
        assert "[MO PHONG THUAT TOAN HEADLESS - KHONG PHAI LIVE GAME]" in last_report_str
        assert service.total_maps_processed == 5
        assert service.tree_planner.allocated_count == 5

        summary = service.get_aggregate_summary()
        assert summary["total_maps_completed"] == 5
        assert summary["total_passive_points"] == 5
        assert summary["current_tree_phase"] == TreePhase.PHASE_1_EARLY_SUSTAIN.value
        assert summary["cumulative_chaos_gain"] > 0
