"""Tests for zone ambient messages."""

import tempfile
from pathlib import Path

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


def test_zone_default_no_ambient():
    """Zone() has empty ambient messages and default interval."""
    zone = Zone(name="test")
    assert zone.ambient_messages == []
    assert zone.ambient_interval == 120


def test_zone_with_ambient_messages():
    """Zone created with ambient_messages and ambient_interval stores them."""
    messages = ["message one", "message two"]
    zone = Zone(name="test", ambient_messages=messages, ambient_interval=60)
    assert zone.ambient_messages == messages
    assert zone.ambient_interval == 60


def test_load_zone_with_ambient():
    """TOML with [ambient] section loads messages and interval."""
    toml_content = """
name = "test_zone"
width = 10
height = 10

[ambient]
interval = 45
messages = [
    "a draft of cold air blows through the room",
    "the fire crackles and pops",
    "you hear muffled conversation from the next room",
]
"""
    with tempfile.NamedTemporaryFile(mode="w", suffix=".toml", delete=False) as f:
        f.write(toml_content)
        temp_path = Path(f.name)

    try:
        zone = load_zone(temp_path)
        assert zone.ambient_interval == 45
        assert len(zone.ambient_messages) == 3
        assert "a draft of cold air blows through the room" in zone.ambient_messages
        assert "the fire crackles and pops" in zone.ambient_messages
        assert (
            "you hear muffled conversation from the next room" in zone.ambient_messages
        )
    finally:
        temp_path.unlink()


def test_load_zone_without_ambient():
    """TOML without [ambient] defaults to empty messages."""
    toml_content = """
name = "simple_zone"
width = 5
height = 5
"""
    with tempfile.NamedTemporaryFile(mode="w", suffix=".toml", delete=False) as f:
        f.write(toml_content)
        temp_path = Path(f.name)

    try:
        zone = load_zone(temp_path)
        assert zone.ambient_messages == []
        assert zone.ambient_interval == 120  # default
    finally:
        temp_path.unlink()


def test_get_ambient_message_returns_from_list():
    """get_ambient_message returns a message from the zone's list."""
    messages = ["message one", "message two", "message three"]
    zone = Zone(name="test", ambient_messages=messages)

    # Run multiple times to ensure we get valid messages
    for _ in range(10):
        msg = get_ambient_message(zone)
        assert msg in messages


def test_get_ambient_message_empty_list_returns_none():
    """get_ambient_message returns None when zone has no messages."""
    zone = Zone(name="test")
    assert get_ambient_message(zone) is None
