from __future__ import annotations

from typing import Tuple

from catan.data import Resource
from catan.game import Game


def find_initial_spot(game: Game) -> Tuple[int, int]:
    board = game.board
    for corner_id in sorted(board.corners, key=board.corner_label):
        if not board.can_place_settlement(corner_id, True):
            continue
        edges = sorted(board.corners[corner_id].edges, key=board.edge_label)
        for edge_id in edges:
            if board.edges[edge_id].owner:
                continue
            return board.corner_label(corner_id), board.edge_label(edge_id)
    raise RuntimeError("No available initial placement")


def find_connected_edge(game: Game) -> int:
    player = game.current_player
    board = game.board
    for edge_id, edge in board.edges.items():
        if edge.owner:
            continue
        if game._road_connection_valid(player, edge):  # noqa: SLF001 - test helper
            return board.edge_label(edge_id)
    raise RuntimeError("No valid edge to extend road network")


def grant_resources(game: Game, player_name: str, amount: int = 5) -> None:
    player = game.player_by_name(player_name)
    for resource in Resource:
        if resource == Resource.DESERT:
            continue
        player.resources[resource] = amount
