from __future__ import annotations

import pytest

from catan.cli import CLIController
from catan.game import Game, GameConfig, Phase
from catan.data import Resource
from tests.utils import find_initial_spot, find_connected_edge, grant_resources


def make_controller(seed: int = 7) -> CLIController:
    game = Game(GameConfig(player_names=["Alice", "Bob", "Cara"], seed=seed))
    controller = CLIController(game)
    _complete_setup(controller)
    return controller


def _complete_setup(controller: CLIController) -> None:
    game = controller.game
    while game.phase != Phase.MAIN:
        corner, road = find_initial_spot(game)
        controller.handle_command(f"place {corner} {road}")


def test_cli_blocks_building_before_roll() -> None:
    controller = make_controller()
    grant_resources(controller.game, controller.game.current_player.name)
    edge_label = find_connected_edge(controller.game)
    with pytest.raises(ValueError):
        controller.handle_command(f"build road {edge_label}")


def test_cli_allows_build_after_roll_and_cost_paid() -> None:
    controller = make_controller()
    player_name = controller.game.current_player.name
    grant_resources(controller.game, player_name)
    edge_label = find_connected_edge(controller.game)
    before = len(controller.game.player_by_name(player_name).roads)
    controller.handle_command("roll")
    controller.handle_command(f"build road {edge_label}")
    player = controller.game.player_by_name(player_name)
    assert len(player.roads) == before + 1
    # Ensure resources spent
    assert player.resources[Resource.BRICK] == 4
    assert player.resources[Resource.LUMBER] == 4


def test_cli_prevents_double_roll() -> None:
    controller = make_controller()
    controller.handle_command("roll")
    with pytest.raises(ValueError):
        controller.handle_command("roll")
