import pytest

from bombahead import CellType, Position
from bombahead.client import decode_cell, parse_classic_state


def test_decode_cell_string_and_numeric_encodings() -> None:
    assert decode_cell("AIR") == CellType.AIR
    assert decode_cell("WALL") == CellType.WALL
    assert decode_cell(0) == CellType.WALL
    assert decode_cell(1) == CellType.AIR
    assert decode_cell(2) == CellType.BOX
    assert decode_cell(99) == CellType.AIR


def test_decode_cell_invalid_encoding() -> None:
    with pytest.raises(ValueError):
        decode_cell(True)


def test_parse_classic_state_assigns_me_and_opponents() -> None:
    payload = {
        "players": [
            {"id": "p1", "pos": {"x": 0, "y": 0}, "health": 3, "score": 1},
            {"id": "p2", "pos": {"x": 1, "y": 0}, "health": 2, "score": 2},
        ],
        "field": {"width": 3, "height": 2, "field": ["AIR", 0, 2, "BOX", "WALL", 1]},
        "bombs": [{"pos": {"x": 1, "y": 1}, "fuse": 2}],
        "explosions": [{"x": 0, "y": 1}],
    }

    state = parse_classic_state(payload, "p2")
    assert state.me is not None
    assert state.me.id == "p2"
    assert len(state.opponents) == 1
    assert state.opponents[0].id == "p1"
    assert state.field.cell_at(Position(1, 0)) == CellType.WALL
    assert state.field.cell_at(Position(2, 0)) == CellType.BOX


def test_parse_classic_state_fallback_without_welcome() -> None:
    payload = {
        "players": [
            {"id": "first", "pos": {"x": 0, "y": 0}, "health": 3, "score": 1},
            {"id": "second", "pos": {"x": 1, "y": 0}, "health": 2, "score": 2},
        ],
        "field": {"width": 1, "height": 1, "field": ["AIR"]},
        "bombs": [],
        "explosions": [],
    }

    state = parse_classic_state(payload, "unknown-id")
    assert state.me is not None
    assert state.me.id == "first"
    assert len(state.opponents) == 1
    assert state.opponents[0].id == "second"


def test_parse_classic_state_invalid_payload() -> None:
    with pytest.raises(ValueError):
        parse_classic_state([], "p1")
