"""Tests for the prompt command."""

from unittest.mock import AsyncMock, MagicMock

import pytest

from mudlib.commands.prompt import cmd_prompt
from mudlib.prompt import render_prompt


@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 player(mock_reader, mock_writer):
    from mudlib.player import Player

    return Player(name="TestPlayer", x=5, y=5, reader=mock_reader, writer=mock_writer)


@pytest.mark.asyncio
async def test_prompt_bare_shows_current_and_variables(player):
    """prompt with no args shows current template and available variables."""
    await cmd_prompt(player, "")
    output = "".join([call[0][0] for call in player.writer.write.call_args_list])
    assert "current" in output.lower()
    assert "variables" in output.lower() or "available" in output.lower()
    # Should list some variables
    assert "stamina" in output.lower()


@pytest.mark.asyncio
async def test_prompt_set_custom_template(player):
    """prompt <template> sets player.prompt_template."""
    custom = "{pl} >"
    await cmd_prompt(player, custom)
    assert player.prompt_template == custom
    # Should confirm it was set
    output = "".join([call[0][0] for call in player.writer.write.call_args_list])
    assert "set" in output.lower() or "prompt" in output.lower()


@pytest.mark.asyncio
async def test_prompt_reset_clears_template(player):
    """prompt reset clears player.prompt_template back to None."""
    player.prompt_template = "{pl} > "
    await cmd_prompt(player, "reset")
    assert player.prompt_template is None
    # Should confirm reset
    output = "".join([call[0][0] for call in player.writer.write.call_args_list])
    assert "reset" in output.lower() or "default" in output.lower()


@pytest.mark.asyncio
async def test_prompt_custom_template_used_in_render(player):
    """After setting custom template, render_prompt uses it."""
    custom = "[{stamina}] > "
    player.prompt_template = custom
    player.stamina = 50
    player.max_stamina = 100
    player.pl = 10
    player.max_pl = 20

    result = render_prompt(player)
    # Should contain the stamina value from our custom template
    assert "[50]" in result or "[50.0]" in result
