from __future__ import annotations

from dataclasses import dataclass, field as dc_field

from .enums import CellType


@dataclass(frozen=True)
class Position:
    x: int
    y: int

    def distance_to(self, other: "Position") -> int:
        return abs(self.x - other.x) + abs(self.y - other.y)


@dataclass(frozen=True)
class Player:
    id: str
    pos: Position
    health: int
    score: int


@dataclass(frozen=True)
class Bomb:
    pos: Position
    fuse: int


@dataclass
class Field:
    width: int
    height: int
    cells: list[CellType] = dc_field(default_factory=list)

    def cell_at(self, pos: Position) -> CellType:
        if pos.x < 0 or pos.x >= self.width or pos.y < 0 or pos.y >= self.height:
            return CellType.WALL

        idx = pos.y * self.width + pos.x
        if idx < 0 or idx >= len(self.cells):
            return CellType.WALL

        return self.cells[idx]


@dataclass
class GameState:
    current_tick: int = 0
    me: Player | None = None
    opponents: list[Player] = dc_field(default_factory=list)
    players: list[Player] = dc_field(default_factory=list)
    field: Field = dc_field(default_factory=lambda: Field(width=0, height=0, cells=[]))
    bombs: list[Bomb] = dc_field(default_factory=list)
    explosions: list[Position] = dc_field(default_factory=list)
