"""Tests for per-zone mob spawn rules."""

import tempfile
from pathlib import Path

from mudlib.zone import SpawnRule, Zone
from mudlib.zones import load_zone


def test_zone_default_no_spawn_rules():
    """Zone() has empty spawn_rules list by default."""
    zone = Zone(name="test", width=10, height=10)
    assert zone.spawn_rules == []


def test_zone_with_spawn_rules():
    """Zone with spawn rules stores them."""
    rule1 = SpawnRule(mob="rat", max_count=3, respawn_seconds=300)
    rule2 = SpawnRule(mob="goblin", max_count=1, respawn_seconds=600)
    zone = Zone(name="test", width=10, height=10, spawn_rules=[rule1, rule2])

    assert len(zone.spawn_rules) == 2
    assert zone.spawn_rules[0].mob == "rat"
    assert zone.spawn_rules[0].max_count == 3
    assert zone.spawn_rules[0].respawn_seconds == 300
    assert zone.spawn_rules[1].mob == "goblin"
    assert zone.spawn_rules[1].max_count == 1
    assert zone.spawn_rules[1].respawn_seconds == 600


def test_load_zone_with_spawn_rules():
    """TOML with [[spawns]] loads spawn rules."""
    toml_content = """
name = "testzone"
width = 10
height = 10

[[spawns]]
mob = "rat"
max_count = 3
respawn_seconds = 300

[[spawns]]
mob = "goblin"
max_count = 1
respawn_seconds = 600
"""
    with tempfile.NamedTemporaryFile(mode="w", suffix=".toml", delete=False) as f:
        f.write(toml_content)
        f.flush()
        temp_path = Path(f.name)

    try:
        zone = load_zone(temp_path)
        assert len(zone.spawn_rules) == 2
        assert zone.spawn_rules[0].mob == "rat"
        assert zone.spawn_rules[0].max_count == 3
        assert zone.spawn_rules[0].respawn_seconds == 300
        assert zone.spawn_rules[1].mob == "goblin"
        assert zone.spawn_rules[1].max_count == 1
        assert zone.spawn_rules[1].respawn_seconds == 600
    finally:
        temp_path.unlink()


def test_load_zone_without_spawn_rules():
    """TOML without spawns defaults to empty list."""
    toml_content = """
name = "testzone"
width = 10
height = 10

[terrain]
rows = [".........."]
"""
    with tempfile.NamedTemporaryFile(mode="w", suffix=".toml", delete=False) as f:
        f.write(toml_content)
        f.flush()
        temp_path = Path(f.name)

    try:
        zone = load_zone(temp_path)
        assert zone.spawn_rules == []
    finally:
        temp_path.unlink()


def test_spawn_rule_fields():
    """SpawnRule has mob, max_count, respawn_seconds fields."""
    rule = SpawnRule(mob="rat", max_count=5, respawn_seconds=120)
    assert rule.mob == "rat"
    assert rule.max_count == 5
    assert rule.respawn_seconds == 120


def test_spawn_rule_defaults():
    """SpawnRule has sensible defaults for max_count and respawn_seconds."""
    rule = SpawnRule(mob="rat")
    assert rule.mob == "rat"
    assert rule.max_count == 1
    assert rule.respawn_seconds == 300
