"""
Adversarial Stress Testing & Security Fuzzing Suite for ZoneEngine (Milestone 1).
Validates:
1. Zone ID Fuzzing (Fail-Safe Closed: Unicode, Null Bytes, SQLi, Path Traversal, Empty).
2. Safe Haven Purity & Zero Hostile Leaks in Hideout and Sanctuary.
3. Spawn Validation Matrix across Diverse Types & Values.
4. Extreme Boundary Coordinate Gating in Player Hideout.
5. Immutability of ZoneDefinition Dataclasses against Direct Tampering.
6. Empirical Verification of Adversarial Edge Cases (Unhashable Types, NaN Coordinates & Type Confusion).
"""

import math
from typing import Any, List
import pytest

from server.world.zone_engine import ZoneEngine
from server.world.zone_types import ZoneType, ZoneDefinition, ZoneEnvironment


@pytest.fixture
def engine() -> ZoneEngine:
    return ZoneEngine()


class TestZoneEngineAdversarialFuzzing:
    """Empirical adversarial fuzzing and stress testing of ZoneEngine."""

    def test_fuzz_zone_ids_fail_safe_closed(self, engine: ZoneEngine) -> None:
        """
        Fuzzes can_spawn_hostile_monsters and validate_monster_spawn with malformed,
        malicious, and boundary string values. All must fail safe (return False).
        """
        malformed_zone_ids: List[Any] = [
            "",
            " ",
            "   \t\n",
            None,
            "zone_player_hideout\x00",
            "zone_player_hideout\n",
            "zone_player_hideout\r\n",
            "ZONE_PLAYER_HIDEOUT",
            "Zone_Player_Hideout",
            "../../etc/passwd",
            "..\\..\\windows\\win.ini",
            "' OR '1'='1",
            "<script>alert(1)</script>",
            "\U0001F480\U00002694\U0001F525",  # Skull, Swords, Fire
            "a" * 10000,
            0,
            12345,
            (1, 2, 3),  # Hashable tuple
        ]

        for zid in malformed_zone_ids:
            # 1. can_spawn_hostile_monsters must return False without unhandled crash
            assert engine.can_spawn_hostile_monsters(zid) is False, (
                f"Security breach: malformed zone_id {repr(zid)} allowed hostile spawning!"
            )

            # 2. validate_monster_spawn(is_dummy=False) must reject
            ok, msg = engine.validate_monster_spawn(zid, is_dummy=False)
            assert ok is False, (
                f"Security breach: validate_monster_spawn allowed hostile mob in {repr(zid)}!"
            )
            assert isinstance(msg, str) and len(msg) > 0

    def test_safe_haven_purity_zero_hostile_leaks(self, engine: ZoneEngine) -> None:
        """
        Guarantees 100% safe haven purity:
        Neither zone_player_hideout nor zone_boundless_sanctuary can ever spawn hostile mobs.
        """
        safe_zones = ["zone_player_hideout", "zone_boundless_sanctuary"]

        for zone_id in safe_zones:
            # Must strictly reject hostile mobs
            assert engine.can_spawn_hostile_monsters(zone_id) is False
            ok, reason = engine.validate_monster_spawn(zone_id, is_dummy=False)
            assert ok is False
            assert "An To\xe0n" in reason or "Sanctuary" in reason or "Nghi\xeam c\u1ea5m" in reason

            # Inanimate Target Dummy is permitted
            ok_dummy, reason_dummy = engine.validate_monster_spawn(zone_id, is_dummy=True)
            assert ok_dummy is True
            assert "Target Dummy" in reason_dummy or "Kh\xf4i L\u1ed7i" in reason_dummy

    def test_wilderness_zones_allow_hostile_spawning(self, engine: ZoneEngine) -> None:
        """Verifies outer exploration zones allow hostile monster spawning."""
        outer_zones = ["zone_tang_kiem_nhai", "zone_ancient_sword_barrow", "zone_boundless_sandstorm"]
        for zone_id in outer_zones:
            assert engine.can_spawn_hostile_monsters(zone_id) is True
            ok, _ = engine.validate_monster_spawn(zone_id, is_dummy=False)
            assert ok is True

    def test_validate_monster_spawn_type_matrix(self, engine: ZoneEngine) -> None:
        """
        Stress-tests validate_monster_spawn across falsy types to ensure
        falsy values are treated as hostile and rejected in safe zones.
        """
        safe_zone = "zone_player_hideout"
        falsy_inputs = [False, None, 0, 0.0, "", (), 0j]

        for val in falsy_inputs:
            ok, _ = engine.validate_monster_spawn(safe_zone, is_dummy=val)
            assert ok is False, f"Falsy value {repr(val)} incorrectly bypassed safe haven gating!"

    def test_extreme_coordinates_bounds_rejection(self, engine: ZoneEngine) -> None:
        """
        Verifies that update_player_position strictly rejects out-of-bounds coordinates
        in zone_player_hideout (bounds: 800x800 -> half_w=400.0, half_h=400.0).
        """
        pid = "adversary_player_01"
        engine.spawn_player(pid, "zone_player_hideout")

        # Initial position must be (0.0, 0.0)
        loc = engine.get_player_location(pid)
        assert loc.x == 0.0
        assert loc.y == 0.0

        extreme_coordinates = [
            (10000.0, -10000.0),
            (-10000.0, 10000.0),
            (400.001, 0.0),
            (-400.001, 0.0),
            (0.0, 400.001),
            (0.0, -400.001),
            (1e12, 0.0),
            (-1e12, 0.0),
            (float("inf"), 0.0),
            (-float("inf"), 0.0),
            (0.0, float("inf")),
            (0.0, -float("inf")),
        ]

        for x, y in extreme_coordinates:
            valid, msg = engine.update_player_position(pid, x, y)
            assert valid is False, f"Coordinate ({x}, {y}) bypassed map boundary check!"
            assert "V\u01b0\u1ee3t qu\xe1 ranh gi\u1edbi" in msg or "ranh gi\u1edbi" in msg
            # Position must remain uncorrupted at initial (0.0, 0.0)
            assert loc.x == 0.0
            assert loc.y == 0.0

        # Boundary limit test: (400.0, 400.0) is exactly on edge (valid)
        valid_edge, _ = engine.update_player_position(pid, 400.0, 400.0)
        assert valid_edge is True
        assert loc.x == 400.0
        assert loc.y == 400.0

    def test_zone_definition_dataclass_frozen_immutability(self, engine: ZoneEngine) -> None:
        """
        Verifies that ZoneDefinition instances are frozen dataclasses and cannot
        be directly mutated at runtime to alter zone_type.
        """
        hideout = engine.get_zone("zone_player_hideout")
        with pytest.raises(Exception):  # FrozenInstanceError
            hideout.zone_type = ZoneType.OPEN_WORLD

    def test_adversarial_unhashable_zone_id_anomaly(self, engine: ZoneEngine) -> None:
        """
        EMPIRICAL CHALLENGER FINDING:
        Demonstrates that unhashable types (list, dict) cause TypeError in dictionary lookup
        because zone_id is not guarded with isinstance(zone_id, str).
        """
        unhashable_inputs = [[], {}, set()]
        for bad_id in unhashable_inputs:
            with pytest.raises(TypeError, match="unhashable type"):
                engine.can_spawn_hostile_monsters(bad_id)  # type: ignore

    def test_adversarial_nan_coordinate_anomaly_detection(self, engine: ZoneEngine) -> None:
        """
        EMPIRICAL CHALLENGER FINDING:
        Demonstrates that IEEE 754 NaN passes boundary check (abs(nan) > 400.0 is False),
        highlighting the need for math.isnan / math.isfinite validation.
        """
        pid = "nan_adversary"
        engine.spawn_player(pid, "zone_player_hideout")
        ok, _ = engine.update_player_position(pid, float("nan"), float("nan"))
        # Document empirical behavior: ok is True because NaN comparisons return False
        assert ok is True, "Empirical reproduction of NaN bypass condition"
        loc = engine.get_player_location(pid)
        assert math.isnan(loc.x)
        assert math.isnan(loc.y)

    def test_adversarial_string_false_type_confusion_anomaly(self, engine: ZoneEngine) -> None:
        """
        EMPIRICAL CHALLENGER FINDING:
        Demonstrates that string 'False' evaluates truthily under `if is_dummy:`.
        If caller passes deserialized string 'False' instead of bool False, it permits the spawn.
        """
        ok, _ = engine.validate_monster_spawn("zone_player_hideout", is_dummy="False")
        # In Python, bool('False') is True, so `if is_dummy:` evaluates to True
        assert ok is True, "Empirical reproduction of string 'False' truthiness condition"
