"""AutoPOE2 - Multi-Map Endurance Simulation & 100% Autonomy Readiness Gate (Chu Kỳ 8).
======================================================================================
[MÔ PHỎNG THUẬT TOÁN HEADLESS - KHÔNG PHẢI LIVE GAME] (Rule 5 Compliance)

Domain: QA & Governance Sentinel (Sư đoàn 4) phối hợp Sư đoàn 1, 2, 3.
Test Suite kiểm chứng độ bền hệ thống tự hành qua chuỗi 20 maps liên tục:
1. Sư đoàn 1 (Core & Combat):
   - Chống chọi Boss Phase Transition (Invulnerability, AOE Blast, Hollow Form Stance).
   - Bất biến INV-CI-01: Life 1/1, Max ES 4284, 0 tử trận (Survival Rate = 100.0%).
2. Sư đoàn 2 (Perception & Navigation):
   - Hiệu chuẩn Camera Zoom Calibrator động (1.0x, 1.4x, 2.0x, Yaw 0-45°).
   - Bất biến INV-WASD-MIN-DWELL: Thời gian giữ phím WASD luôn >= 0.30s (300ms).
3. Sư đoàn 3 (Endgame Loop & Economic Logistics):
   - Tiêu hao Waystone và tự động tái nạp (Restock) từ Stash Map Tab khi túi còn < 2 Waystones.
   - Sàn Faustus Currency Waterfall Cascade & Auto-Profit Taking (chốt lời phụ tệ sang Chaos/Divine).
   - Bất biến INV-EXCHANGE-GOLD-TAX: Quỹ vàng an toàn luôn >= 5,000 Gold.
   - Cây nội tại Atlas Progression DAG 115+ nodes: Nhận +20 điểm nội tại tuần tự.
4. Sư đoàn 4 (QA & Governance Sentinel):
   - LiveRunSentinel giám sát thụ động (Zero-Input Guarantee) suốt 20 maps.
   - Xác nhận 0 bất thường, 100% Healthy.
"""

from __future__ import annotations

import os
import pytest
from typing import Dict, List

from tests.helpers.multi_map_endurance_harness import (
    EnduranceSimulationReport,
    MultiMapEnduranceHarness,
)


@pytest.fixture(scope="module")
def endurance_report() -> EnduranceSimulationReport:
    """Fixture thực thi một lần toàn bộ chuỗi mô phỏng 20 maps để tái sử dụng kết quả kiểm thử."""
    harness = MultiMapEnduranceHarness(
        initial_gold=10000,
        initial_waystones_in_bag=5,
        initial_waystones_in_stash=30,
        random_seed=20260918,
    )
    return harness.run_endurance_simulation(total_maps=20)


class TestMultiMapEnduranceSimulation:
    """Bộ kiểm thử nghiệm thu toàn diện độ bền Multi-Map và chỉ số Sẵn Sàng 100% Autonomy."""

    def test_full_20_maps_endurance_survival_100_percent(self, endurance_report: EnduranceSimulationReport):
        """[MÔ PHỎNG THUẬT TOÁN HEADLESS - KHÔNG PHẢI LIVE GAME]
        Xác nhận hoàn thành đủ 20 maps với tỷ lệ sống sót tuyệt đối 100.0% (0 tử trận).
        """
        assert endurance_report.total_maps_run == 20
        assert endurance_report.total_deaths == 0, f"Có {endurance_report.total_deaths} ca tử trận ngoài ý muốn!"
        assert endurance_report.survival_rate_pct == 100.0, "Survival Rate không đạt 100.0%!"
        assert len(endurance_report.map_records) == 20

        for rec in endurance_report.map_records:
            assert rec.survived is True
            assert rec.hp_min == 1, "Bất biến INV-CI-01 bị vi phạm: HP khác 1!"
            assert rec.es_min > 0, f"Map {rec.map_index}: ES bị tụt về 0!"

    def test_boss_phase_transition_resilience_zero_deaths(self, endurance_report: EnduranceSimulationReport):
        """[MÔ PHỎNG THUẬT TOÁN HEADLESS - KHÔNG PHẢI LIVE GAME]
        [Sư đoàn 1] Chống chọi an toàn qua tất cả các đợt Boss Phase Transition (AOE/Invulnerable).
        """
        assert endurance_report.boss_phases_survived >= 5, (
            f"Số pha Boss sống sót ({endurance_report.boss_phases_survived}) chưa đủ mẫu kiểm định!"
        )

        boss_records = [r for r in endurance_report.map_records if r.boss_phase_triggered]
        for b_rec in boss_records:
            assert b_rec.es_min >= 2000, (
                f"Map {b_rec.map_index} Boss Phase: ES tụt quá sâu ({b_rec.es_min} < 2000)!"
            )
            assert b_rec.hp_min == 1

    def test_camera_minimap_calibrator_dynamic_zoom_and_dwell(self, endurance_report: EnduranceSimulationReport):
        """[MÔ PHỎNG THUẬT TOÁN HEADLESS - KHÔNG PHẢI LIVE GAME]
        [Sư đoàn 2] Kiểm chứng hiệu chuẩn Camera/Minimap động trên 20 maps và bất biến Dwell Time >= 0.30s.
        """
        assert endurance_report.camera_calibrations_performed == 20

        zoom_levels_seen = set()
        for rec in endurance_report.map_records:
            zoom_levels_seen.add(rec.zoom_level)
            # Bất biến INV-WASD-MIN-DWELL
            assert rec.wasd_dwell_sec >= 0.30, (
                f"Map {rec.map_index}: Dwell time {rec.wasd_dwell_sec:.3f}s vi phạm INV-WASD-MIN-DWELL!"
            )

        # Bảo đảm đã kiểm thử qua đa dạng mức độ zoom
        assert len(zoom_levels_seen) >= 3, f"Chưa kiểm thử đủ các mức zoom (hiện có: {zoom_levels_seen})"

    def test_faustus_profit_taking_and_waystone_restock_logistics(self, endurance_report: EnduranceSimulationReport):
        """[MÔ PHỎNG THUẬT TOÁN HEADLESS - KHÔNG PHẢI LIVE GAME]
        [Sư đoàn 3] Kiểm chứng tiêu hao 20 waystones, tự động restock từ Stash và quỹ vàng sàn >= 5000 Gold.
        """
        assert endurance_report.total_waystones_consumed == 20
        assert endurance_report.total_waystones_restocked >= 15, (
            f"Waystone tái nạp ({endurance_report.total_waystones_restocked}) không đủ đáp ứng tiêu hao 20 maps!"
        )
        assert endurance_report.arbitrage_sessions_executed == 10  # 10 đợt chốt lời (mỗi 2 maps 1 lần)

        for rec in endurance_report.map_records:
            assert rec.waystones_in_inventory >= 1, f"Map {rec.map_index}: Túi cạn sạch Waystone!"
            assert rec.ending_gold >= 5000, (
                f"Map {rec.map_index}: Quỹ vàng tụt xuống {rec.ending_gold} < 5,000 Gold (vi phạm INV-EXCHANGE-GOLD-TAX)!"
            )

    def test_live_sentinel_zero_anomalies_gating_throughout_20_maps(self, endurance_report: EnduranceSimulationReport):
        """[MÔ PHỎNG THUẬT TOÁN HEADLESS - KHÔNG PHẢI LIVE GAME]
        [Sư đoàn 4] Xác nhận LiveRunSentinel giám sát thụ động 100% Healthy, không có bất kỳ dị thường nào.
        """
        assert endurance_report.sentinel_anomalies_detected == 0
        assert endurance_report.sentinel_health_pct == 100.0

        for rec in endurance_report.map_records:
            assert rec.sentinel_healthy is True, f"Map {rec.map_index}: LiveRunSentinel phát hiện lỗi bất biến!"

    def test_economic_net_worth_growth_delta_chaos_and_divine(self, endurance_report: EnduranceSimulationReport):
        """[MÔ PHỎNG THUẬT TOÁN HEADLESS - KHÔNG PHẢI LIVE GAME]
        Kiểm chứng tăng trưởng tài sản ròng thực chất sau 20 maps: Delta Chaos > 0 và Delta Divine > 0.
        """
        assert endurance_report.delta_net_worth_chaos > 200.0, (
            f"Tăng trưởng tài sản ròng {endurance_report.delta_net_worth_chaos} Chaos quá thấp!"
        )
        assert endurance_report.delta_net_worth_divine > 1.0, (
            f"Tăng trưởng Divine {endurance_report.delta_net_worth_divine} Divine quá thấp!"
        )
        assert endurance_report.final_net_worth_chaos > endurance_report.initial_net_worth_chaos
        assert endurance_report.final_gold_balance >= 10000

    def test_atlas_progression_dag_tree_expansion_over_20_maps(self, endurance_report: EnduranceSimulationReport):
        """[MÔ PHỎNG THUẬT TOÁN HEADLESS - KHÔNG PHẢI LIVE GAME]
        Kiểm chứng mở rộng cây nội tại Atlas qua 20 maps hoàn thành bonus.
        """
        # Mỗi map hoàn thành có bonus tích lũy 1 điểm Atlas Passive
        # Kiểm tra qua map record cuối cùng
        last_record = endurance_report.map_records[-1]
        assert last_record.map_index == 20
        assert endurance_report.average_clear_time_sec <= 60.0, (
            f"Tốc độ dọn map trung bình {endurance_report.average_clear_time_sec}s quá chậm (> 60s)!"
        )
