"""A small Generals WebSocket player. Change choose_action to improve it."""

import asyncio
import json
import os
from typing import Literal

from pydantic import BaseModel
from websockets.asyncio.client import connect


class Message(BaseModel):
    type: Literal["hello", "observation", "final", "error", "failure"]


class Observation(BaseModel):
    protocol_version: Literal[1]
    turn: int
    eliminated: bool
    height: int
    width: int
    type_grid: list[list[int]]
    owner_grid: list[list[int]]
    army_grid: list[list[int]]


def choose_action(obs: Observation) -> list[int]:
    """Move the largest available army into a weaker adjacent enemy or neutral tile."""
    moves: list[tuple[int, list[int]]] = []
    for row in range(obs.height):
        for col in range(obs.width):
            army = obs.army_grid[row][col]
            if obs.owner_grid[row][col] != 1 or army < 2:
                continue
            for direction, (dr, dc) in enumerate(((-1, 0), (1, 0), (0, -1), (0, 1))):
                r, c = row + dr, col + dc
                if (
                    0 <= r < obs.height
                    and 0 <= c < obs.width
                    and obs.type_grid[r][c] in (1, 3, 4)
                    and obs.owner_grid[r][c] != 1
                    and army - 1 > obs.army_grid[r][c]
                ):
                    moves.append((army, [0, row, col, direction, 0]))
    return max(moves)[1] if moves else [1, 0, 0, 0, 0]


async def main() -> None:
    async with connect(os.environ["COWORLD_PLAYER_WS_URL"], ping_timeout=None) as ws:
        async for raw in ws:
            message = Message.model_validate_json(raw)
            if message.type == "final":
                print(raw)
                return
            if message.type in ("error", "failure"):
                raise RuntimeError(raw)
            if message.type == "observation":
                obs = Observation.model_validate_json(raw)
                if not obs.eliminated:
                    await ws.send(json.dumps({"type": "action", "turn": obs.turn, "action": choose_action(obs)}))
        raise RuntimeError("Game connection closed before the final result")


asyncio.run(main())
