"""Baseline controllers for Phase 3c (before NEAT evolution)."""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from protocol import StateMessage


class NoOpController:
    """Controller that takes no action (all inputs 0)."""

    def act(self, state: StateMessage) -> int:
        return 0


class FixedCenterController:
    """
    Controller that moves the player to the center of the screen.

    Reads current player position and issues input to move towards center.
    """

    def __init__(self, center_x: float = 192.0, center_y: float = 224.0):
        self.center_x = center_x
        self.center_y = center_y

    def act(self, state: StateMessage) -> int:
        dx = self.center_x - state.player_x
        dy = self.center_y - state.player_y

        action = 0
        if abs(dx) > 5:
            action |= 0x02 if dx > 0 else 0x01  # right = 2, left = 1
        if abs(dy) > 5:
            action |= 0x08 if dy > 0 else 0x04  # down = 8, up = 4
        return action


class RandomController:
    """Controller that selects a random action (for baseline)."""

    def __init__(self, seed: int | None = None):
        import random

        self.random = random.Random(seed)

    def act(self, state: StateMessage) -> int:
        return self.random.randint(0, 255)


class NearestThreatDodgeController:
    """
    Controller that attempts to dodge nearest bullets.

    For each bullet, compute the vector from player to bullet. Issue input
    to move opposite direction. If closest bullet is within threshold distance,
    prioritize dodging.
    """

    def __init__(self, dodge_threshold: float = 40.0, flee_radius: float = 200.0):
        self.dodge_threshold = dodge_threshold
        self.flee_radius = flee_radius

    def act(self, state: StateMessage) -> int:
        if not state.bullets:
            return 0

        # Find closest bullet
        closest_bullet = min(state.bullets, key=lambda b: (b.x - state.player_x) ** 2 + (b.y - state.player_y) ** 2)

        dx = closest_bullet.x - state.player_x
        dy = closest_bullet.y - state.player_y
        dist = (dx ** 2 + dy ** 2) ** 0.5

        action = 0
        if dist > self.flee_radius:
            return action

        # Move away from bullet
        if abs(dx) > 5:
            action |= 0x01 if dx < 0 else 0x02  # if bullet is left, move left
        if abs(dy) > 5:
            action |= 0x08 if dy < 0 else 0x04

        return action


class ReplayController:
    """
    Controller that replays a pre-recorded action trace.

    Maintains a circular buffer of actions indexed by frame number.
    """

    def __init__(self, action_trace: list[int]):
        self.action_trace = action_trace
        self.frame_offset = 0

    def act(self, state: StateMessage) -> int:
        if not self.action_trace:
            return 0
        idx = (state.frame_number + self.frame_offset) % len(self.action_trace)
        return self.action_trace[idx]