"""Tests for portal display in look command."""

from unittest.mock import AsyncMock, MagicMock

import pytest

from mudlib.player import Player
from mudlib.portal import Portal
from mudlib.zone import Zone


@pytest.fixture
def mock_writer():
    writer = MagicMock()
    writer.write = MagicMock()
    writer.drain = AsyncMock()
    return writer


@pytest.fixture
def mock_reader():
    return MagicMock()


@pytest.fixture
def test_zone():
    terrain = [["." for _ in range(10)] for _ in range(10)]
    return Zone(
        name="testzone",
        width=10,
        height=10,
        toroidal=True,
        terrain=terrain,
    )


@pytest.fixture
def player(mock_reader, mock_writer, test_zone):
    p = Player(
        name="TestPlayer",
        x=5,
        y=5,
        reader=mock_reader,
        writer=mock_writer,
        location=test_zone,
    )
    return p


@pytest.mark.asyncio
async def test_look_shows_portal_at_position(player, test_zone, mock_writer):
    """look command shows portals at player position."""
    from mudlib.commands.look import cmd_look

    Portal(
        name="shimmering doorway",
        location=test_zone,
        x=5,
        y=5,
        target_zone="elsewhere",
        target_x=0,
        target_y=0,
    )

    await cmd_look(player, "")
    output = "".join([call[0][0] for call in mock_writer.write.call_args_list])
    # New format: "You see {portal.name}."
    assert "you see shimmering doorway." in output.lower()


@pytest.mark.asyncio
async def test_look_shows_multiple_portals(player, test_zone, mock_writer):
    """look command shows multiple portals at player position."""
    from mudlib.commands.look import cmd_look

    Portal(
        name="red portal",
        location=test_zone,
        x=5,
        y=5,
        target_zone="redzone",
        target_x=0,
        target_y=0,
    )
    Portal(
        name="blue portal",
        location=test_zone,
        x=5,
        y=5,
        target_zone="bluezone",
        target_x=0,
        target_y=0,
    )

    await cmd_look(player, "")
    output = "".join([call[0][0] for call in mock_writer.write.call_args_list])
    assert "red portal" in output.lower()
    assert "blue portal" in output.lower()


@pytest.mark.asyncio
async def test_look_no_portals_at_position(player, test_zone, mock_writer):
    """look command doesn't show portals when none at position."""
    from mudlib.commands.look import cmd_look

    Portal(
        name="distant portal",
        location=test_zone,
        x=8,
        y=8,
        target_zone="elsewhere",
        target_x=0,
        target_y=0,
    )

    await cmd_look(player, "")
    output = "".join([call[0][0] for call in mock_writer.write.call_args_list])
    # Should not mention portals when none are at player position
    assert "portal" not in output.lower() or "distant portal" not in output.lower()
