from __future__ import annotations

import math
import random
from typing import Any, Dict, List, Optional, Tuple, Union


class Vector(tuple):
    """A 2D Vector supporting arithmetic and geometric operations."""

    def __new__(cls, x, y):
        return tuple.__new__(Vector, (float(x), float(y)))

    def __init__(self, x, y):
        self.x = float(x)
        self.y = float(y)

    def __eq__(self, other):
        if not isinstance(other, (Vector, tuple, list)) or len(other) != 2:
            return False
        return math.isclose(self.x, other[0], abs_tol=1e-7) and math.isclose(self.y, other[1], abs_tol=1e-7)

    def __add__(self, other):
        return Vector(self.x + other[0], self.y + other[1])

    def __sub__(self, other):
        return Vector(self.x - other[0], self.y - other[1])

    def __neg__(self):
        return Vector(-self.x, -self.y)

    def __mul__(self, other):
        if isinstance(other, (Vector, tuple, list)):
            return self.x * other[0] + self.y * other[1]
        return Vector(self.x * other, self.y * other)

    def __rmul__(self, other):
        if isinstance(other, (Vector, tuple, list)):
            return self.x * other[0] + self.y * other[1]
        return Vector(self.x * other, self.y * other)

    def __truediv__(self, other):
        return Vector(self.x / other, self.y / other)

    def __abs__(self):
        return self.length()

    def length_sq(self) -> float:
        """Returns the squared Euclidean length."""
        return self.x * self.x + self.y * self.y

    def length(self) -> float:
        """Returns the Euclidean length."""
        return math.hypot(self.x, self.y)

    def normalize(self) -> "Vector":
        """Returns unit vector in the same direction, or Vector(0, 0) if zero."""
        l = self.length()
        if l == 0.0:
            return Vector(0.0, 0.0)
        return Vector(self.x / l, self.y / l)

    def dot(self, other) -> float:
        """Dot product with another 2D vector."""
        return self.x * other[0] + self.y * other[1]

    def direction_to(self, point) -> "Vector":
        """Unit vector pointing from self to point."""
        diff = Vector(point[0] - self.x, point[1] - self.y)
        return diff.normalize()

    def distance_sq_to(self, point) -> float:
        """Squared Euclidean distance to point."""
        return (self.x - point[0]) ** 2 + (self.y - point[1]) ** 2

    def distance_to(self, point) -> float:
        """Euclidean distance to point."""
        return math.hypot(self.x - point[0], self.y - point[1])

    def angle_to(self, point) -> float:
        """Smallest unsigned angle to a given vector."""
        v1 = self.normalize()
        v2 = Vector(point[0], point[1]).normalize()
        dot_prod = max(-1.0, min(1.0, v1.dot(v2)))
        return math.acos(dot_prod)

    def orthogonal(self) -> "Vector":
        """Orthogonal vector pointing 90 degrees right."""
        return Vector(self.y, -self.x)

    def orthonormal(self) -> "Vector":
        """Unit orthogonal vector pointing 90 degrees right."""
        return self.orthogonal().normalize()

    def cross(self, other) -> float:
        """2D cross product determinant (x1*y2 - y1*x2)."""
        return self.x * other[1] - self.y * other[0]

    def determinant(self, start, point) -> float:
        stop = start + self
        return (stop.x - start.x) * (point[1] - start.y) - (stop.y - start.y) * (point[0] - start.x)

    def side(self, start, point) -> float:
        """Returns -1 if point is on the left and +1 if on the right."""
        return math.copysign(1.0, -self.determinant(start, point))


class Obstacle:
    """Base class for obstacles detected by actors."""

    def __init__(self, position):
        self.pos = Vector(position[0], position[1])


class Circle(Obstacle):
    """Circular obstacle with radius."""

    def __init__(self, position, radius: float):
        super().__init__(position)
        self.rad = float(radius)
        self.rad_sq = self.rad ** 2


class Wall(Obstacle):
    """Straight boundary or obstacle wall."""

    def __init__(self, start, stop):
        self.start = Vector(start[0], start[1])
        self.stop = Vector(stop[0], stop[1])
        self.center = (self.start + self.stop) / 2.0
        self.vector = self.stop - self.start
        self.length = self.vector.length()
        super().__init__(self.center)

    def determinant(self, point) -> float:
        return (self.stop.x - self.start.x) * (point[1] - self.start.y) - (self.stop.y - self.start.y) * (point[0] - self.start.x)

    def side(self, point) -> float:
        return math.copysign(1.0, -self.determinant(point))

    def orthonormal_vector_to(self, point) -> Vector:
        return self.side(point) * self.vector.orthonormal()

    def distance_to(self, point) -> float:
        if self.length == 0:
            return self.start.distance_to(point)
        return abs(self.determinant(point) / self.length)

    def distance_sq_to(self, point) -> float:
        if self.length == 0:
            return self.start.distance_sq_to(point)
        return (self.determinant(point) / self.length) ** 2

    def intersects(self, point, vector) -> bool:
        r = self.vector
        s = vector
        q = point
        p = self.start
        r_x_s = r.cross(s)
        if abs(r_x_s) >= 1e-6:
            t = (q - p).cross(s / r_x_s)
            u = (p - q).cross(r / (-r_x_s))
            if 0.0 <= t <= 1.0 and 0.0 <= u <= 1.0:
                return True
        return False


# Global force coefficients matching Reynolds model and demo-boids
AVOIDANCE_STRENGTH = 100.0
SEPARATION_STRENGTH = 4.0
SEPARATION_RADIUS = 20.0
SEP_RAD_SQ = SEPARATION_RADIUS ** 2
ALIGNMENT_STRENGTH = 1.5
COHESION_STRENGTH = 1.0
EVASION_STRENGTH = 100.0
PURSUIT_STRENGTH = EVASION_STRENGTH


class Actor:
    """Base class for simulated actors (Boids, Predators)."""

    def __init__(self, simulation, position, velocity, max_speed=0.12, view_distance=60.0,
                 view_angle=math.pi * 1.5, mass=5000.0, color=(255, 255, 0)):
        self.sim = simulation
        self.pos = Vector(position[0], position[1])
        norm_v = Vector(velocity[0], velocity[1]).normalize()
        if norm_v.length_sq() == 0:
            norm_v = Vector(1.0, 0.0)
        self.direction = norm_v
        self.dir_history = [self.direction] * 8
        self.max_speed = float(max_speed)
        self.v = self.direction * self.max_speed
        self.speed = self.max_speed
        self.forces = Vector(0.0, 0.0)
        self.view_dist = float(view_distance)
        self.view_dist_sq = self.view_dist ** 2
        self.view_angle = float(view_angle)
        self.ahead = self.v
        self.mass = float(mass)
        self.color = color

    def update(self, dt: float):
        self.forces += self.calc_avoidance()
        acceleration = self.forces / self.mass
        self.v += acceleration * dt

        self.speed = self.v.length()
        if self.speed > self.max_speed:
            self.v = self.v.normalize() * self.max_speed
            self.speed = self.max_speed
        elif self.speed < 1e-4:
            self.v = self.direction * 0.01
            self.speed = 0.01

        self.direction = self.v.normalize()
        if len(self.dir_history) > 0:
            self.dir_history.pop(0)
        self.dir_history.append(self.direction)

        self.forces = Vector(0.0, 0.0)

        # Boundary bounce check
        if not (0 <= self.pos.x <= self.sim.window_size.x and 0 <= self.pos.y <= self.sim.window_size.y):
            self.v = (self.sim.center - self.pos).normalize() * self.max_speed

        self.pos += self.v * dt
        # TODO implement periodic boundary conditions
        #self.pos %= self.sim.window_size
        self.ahead = 40.0 * self.v * (dt / 16.0)

    def calc_avoidance(self) -> Vector:
        small_ahead = self.ahead / 2.0
        threat: Optional[Obstacle] = None
        threat_dist_sq: Optional[float] = None

        for obstacle in self.sim.obstacles:
            if isinstance(obstacle, Wall):
                dist_sq = max(1e-6, obstacle.distance_sq_to(self.pos))
                if threat_dist_sq is None or dist_sq < threat_dist_sq:
                    if obstacle.intersects(self.pos, self.ahead):
                        threat = obstacle
                        threat_dist_sq = dist_sq
            elif isinstance(obstacle, Circle):
                dist_sq = max(1e-6, self.pos.distance_sq_to(obstacle.pos) - obstacle.rad_sq)
                if threat_dist_sq is None or dist_sq < threat_dist_sq:
                    close_dist_sq = (self.pos + small_ahead).distance_sq_to(obstacle.pos)
                    far_dist_sq = (self.pos + self.ahead).distance_sq_to(obstacle.pos)
                    if close_dist_sq <= obstacle.rad_sq or far_dist_sq <= obstacle.rad_sq or dist_sq <= obstacle.rad_sq:
                        threat = obstacle
                        threat_dist_sq = dist_sq

        if isinstance(threat, Wall) and threat_dist_sq is not None:
            threat_dist = max(1.0, math.sqrt(threat_dist_sq))
            return threat.orthonormal_vector_to(self.pos) * (AVOIDANCE_STRENGTH / threat_dist)
        elif isinstance(threat, Circle) and threat_dist_sq is not None:
            threat_dist = max(1.0, math.sqrt(threat_dist_sq))
            return (self.pos - threat.pos).normalize() * (AVOIDANCE_STRENGTH / threat_dist)
        return Vector(0.0, 0.0)

    def in_fov(self, point) -> bool:
        facing_direction = self.v.normalize()
        to_point = self.pos.direction_to(point)
        return to_point.angle_to(facing_direction) <= (self.view_angle / 2.0)


class Boid(Actor):
    """Flocking boid following separation, alignment, cohesion, obstacle avoidance, and predator evasion."""

    def __init__(self, simulation, position, velocity, max_speed=0.12, view_distance=60.0,
                 view_angle=math.pi * 1.5, mass=5000.0, color=(255, 255, 0)):
        super().__init__(simulation, position, velocity, max_speed, view_distance, view_angle, mass, color)
        self.neighbors: List["Boid"] = []
        self.flocking = Vector(0.0, 0.0)
        self.update_this_frame = bool(random.getrandbits(1))

    def update(self, dt: float):
        if self.update_this_frame:
            self.get_neighbors()
            self.calc_flocking()

        self.forces += self.flocking
        self.forces += self.calc_evasion()
        super().update(dt)
        self.change_color()
        self.update_this_frame = not self.update_this_frame

    def change_color(self):
        ratio = max(0.0, min(1.0, self.speed / self.max_speed))
        red_val = int((1.0 - ratio) * 255)
        self.color = (red_val, 255, 0)

    def get_neighbors(self):
        self.neighbors = []
        for member in self.sim.flock:
            if member is self:
                continue
            if self.pos.distance_sq_to(member.pos) <= self.view_dist_sq and self.in_fov(member.pos):
                self.neighbors.append(member)

    def get_threat(self) -> Tuple[Optional["Predator"], Optional[float]]:
        closest_threat = None
        closest_dist_sq = None
        for threat in self.sim.predators:
            dist_sq = self.pos.distance_sq_to(threat.pos)
            if dist_sq <= self.view_dist_sq and self.in_fov(threat.pos):
                if closest_threat is None or dist_sq < closest_dist_sq:
                    closest_threat = threat
                    closest_dist_sq = dist_sq
        return closest_threat, closest_dist_sq

    def calc_flocking(self):
        separation = self.calc_separation()
        alignment = self.calc_alignment()
        cohesion = self.calc_cohesion()
        self.flocking = separation + alignment + cohesion

    def calc_separation(self) -> Vector:
        if not self.neighbors:
            return Vector(0.0, 0.0)
        avg_evasion = Vector(0.0, 0.0)
        close_neighbors = 0
        for neighbor in self.neighbors:
            dist_sq = self.pos.distance_sq_to(neighbor.pos)
            if dist_sq <= SEP_RAD_SQ and dist_sq > 1e-6:
                close_neighbors += 1
                avg_evasion += (self.pos - neighbor.pos) / math.sqrt(dist_sq)
        if close_neighbors == 0:
            return Vector(0.0, 0.0)
        avg_evasion /= close_neighbors
        return avg_evasion.normalize() * SEPARATION_STRENGTH

    def calc_alignment(self) -> Vector:
        if not self.neighbors:
            return Vector(0.0, 0.0)
        avg_direction = self.v.normalize()
        for neighbor in self.neighbors:
            avg_direction += neighbor.v.normalize()
        avg_direction /= (len(self.neighbors) + 1)
        return avg_direction.normalize() * ALIGNMENT_STRENGTH

    def calc_cohesion(self) -> Vector:
        if not self.neighbors:
            return Vector(0.0, 0.0)
        avg_position = self.pos
        for neighbor in self.neighbors:
            avg_position += neighbor.pos
        avg_position /= (len(self.neighbors) + 1)
        diff = avg_position - self.pos
        if diff.length_sq() == 0:
            return Vector(0.0, 0.0)
        return diff.normalize() * COHESION_STRENGTH

    def calc_evasion(self) -> Vector:
        threat, dist_sq = self.get_threat()
        if threat is None or dist_sq is None:
            return Vector(0.0, 0.0)
        distance = max(1.0, math.sqrt(dist_sq))
        direction = threat.v.side(threat.pos, self.pos) * threat.v.orthonormal()
        return direction * (EVASION_STRENGTH / distance)


class Predator(Actor):
    """Predator actor hunting boids."""

    def __init__(self, simulation, position, velocity, max_speed=0.14, view_distance=200.0,
                 view_angle=math.pi, mass=5000.0, color=(255, 60, 60)):
        super().__init__(simulation, position, velocity, max_speed, view_distance, view_angle, mass, color)
        self.update_this_frame = bool(random.getrandbits(1))

    def update(self, dt: float):
        if self.update_this_frame:
            self.forces += self.calc_pursuit(dt)
        super().update(dt)
        self.update_this_frame = not self.update_this_frame

    def calc_pursuit(self, dt: float) -> Vector:
        target, dist_sq = self.find_target()
        if target is None or dist_sq is None:
            return Vector(0.0, 0.0)
        dist = max(1.0, math.sqrt(dist_sq))
        lead_pos = target.pos + target.v * (40.0 * dt / 16.0)
        direction = self.pos.direction_to(lead_pos)
        return direction * (PURSUIT_STRENGTH / dist)

    def find_target(self) -> Tuple[Optional[Boid], Optional[float]]:
        closest_target = None
        closest_dist_sq = None
        for target in self.sim.flock:
            dist_sq = self.pos.distance_sq_to(target.pos)
            if dist_sq <= self.view_dist_sq and self.in_fov(target.pos):
                if closest_target is None or dist_sq < closest_dist_sq:
                    closest_target = target
                    closest_dist_sq = dist_sq
        return closest_target, closest_dist_sq


class Simulation:
    """Orchestrates actors, obstacles, and time-step updates."""

    def __init__(self, window_size=(800, 500), nboids=35):
        self.window_size = Vector(window_size[0], window_size[1])
        self.center = Vector(window_size[0] / 2.0, window_size[1] / 2.0)
        self.actors: List[Actor] = []
        self.flock: List[Boid] = []
        self.predators: List[Predator] = []
        self.obstacles: List[Obstacle] = []
        self.nboids = nboids
        self.boid_settings = {
            "max_speed": 0.12,
            "view_distance": 60.0,
            "view_angle": math.pi * 1.5,
            "mass": 5000.0,
            "color": (255, 255, 0),
        }

    def setup_boundary_walls(self):
        """Creates perimeter boundary walls enclosing the arena."""
        top_wall = Wall((0, 0), (self.window_size.x, 0))
        right_wall = Wall((self.window_size.x, 0), (self.window_size.x, self.window_size.y))
        bottom_wall = Wall((self.window_size.x, self.window_size.y), (0, self.window_size.y))
        left_wall = Wall((0, self.window_size.y), (0, 0))
        self.add_obstacles(top_wall, right_wall, bottom_wall, left_wall)

    def add_obstacles(self, *args):
        for obs in args:
            self.obstacles.append(obs)

    def clear_obstacles(self):
        del self.obstacles[4:]

    def add_boids(self, n: int, positions=None, velocities=None):
        for i in range(n):
            if positions is not None and i < len(positions):
                pos = positions[i]
            else:
                pos = (random.uniform(50, self.window_size.x - 50), random.uniform(50, self.window_size.y - 50))

            if velocities is not None and i < len(velocities):
                vel = velocities[i]
            else:
                ang = random.uniform(0, 2 * math.pi)
                vel = (math.cos(ang), math.sin(ang))

            boid = Boid(
                simulation=self,
                position=pos,
                velocity=vel,
                max_speed=self.boid_settings["max_speed"],
                view_distance=self.boid_settings["view_distance"],
                view_angle=self.boid_settings["view_angle"],
                mass=self.boid_settings["mass"],
                color=self.boid_settings["color"],
            )
            self.flock.append(boid)
            self.actors.append(boid)

    def add_predator(self, position=None, velocity=None, max_speed=0.14, view_distance=200.0,
                     view_angle=math.pi, mass=5000.0, color=(255, 65, 65)):
        if position is None:
            position = (self.center.x, self.center.y)
        if velocity is None:
            ang = random.uniform(0, 2 * math.pi)
            velocity = (math.cos(ang), math.sin(ang))

        predator = Predator(
            simulation=self,
            position=position,
            velocity=velocity,
            max_speed=max_speed,
            view_distance=view_distance,
            view_angle=view_angle,
            mass=mass,
            color=color,
        )
        self.predators.append(predator)
        self.actors.append(predator)

    def step(self, dt: float):
        for actor in self.actors:
            actor.update(dt)


def simulate_boids(
    duration_seconds: float = 8.0,
    fps: int = 30,
    preset: str = "flock",
    nboids: int = 35,
    width: int = 800,
    height: int = 500,
) -> Dict[str, Any]:
    """
    Simulates Craig Reynolds' boids flocking algorithm with obstacle avoidance and predator pursuit.
    Precomputed on the backend to deliver an immediate, reproducible, and efficient payload for canvas playback.
    """
    preset_clean = (preset or "flock").lower().strip()
    sim = Simulation(window_size=(width, height), nboids=nboids)
    sim.setup_boundary_walls()

    # Configure scene based on requested preset
    if preset_clean == "obstacles":
        # Add circular pillars and a central baffle wall
        sim.add_obstacles(
            Circle((width * 0.25, height * 0.35), 32),
            Circle((width * 0.75, height * 0.65), 36),
            Circle((width * 0.50, height * 0.50), 40),
            Wall((width * 0.40, height * 0.15), (width * 0.60, height * 0.15)),
        )
        sim.add_boids(nboids)

    elif preset_clean == "predator":
        # Flocking boids hunted by a predator
        sim.add_boids(nboids)
        sim.add_predator(position=(sim.center.x, sim.center.y))

    elif preset_clean in ("dense", "chaos"):
        # Larger flock with both obstacles and a hunting predator
        sim.add_obstacles(
            Circle((width * 0.30, height * 0.50), 35),
            Circle((width * 0.70, height * 0.50), 35),
        )
        sim.add_boids(max(nboids, 50))
        sim.add_predator(position=(sim.center.x, sim.center.y))

    else:
        # Default fallback: pure flocking
        preset_clean = "flock"
        sim.add_boids(nboids)

    total_frames = int(duration_seconds * fps)
    dt = 1000.0 / fps  # milliseconds per frame

    serialized_obstacles = []
    # Index 0..3 are perimeter walls
    for obs in sim.obstacles[4:]:
        if isinstance(obs, Circle):
            serialized_obstacles.append({
                "type": "circle",
                "x": round(obs.pos.x, 1),
                "y": round(obs.pos.y, 1),
                "r": round(obs.rad, 1),
            })
        elif isinstance(obs, Wall):
            serialized_obstacles.append({
                "type": "wall",
                "x1": round(obs.start.x, 1),
                "y1": round(obs.start.y, 1),
                "x2": round(obs.stop.x, 1),
                "y2": round(obs.stop.y, 1),
            })

    frames: List[Dict[str, Any]] = []

    for f_idx in range(total_frames):
        boid_records = []
        for b in sim.flock:
            # Average direction of recent frames to smooth rendering
            avg_dir = Vector(0.0, 0.0)
            for d in b.dir_history:
                avg_dir += d
            avg_dir = avg_dir.normalize()
            if avg_dir.length_sq() == 0:
                avg_dir = b.direction

            boid_records.append([
                round(b.pos.x, 1),
                round(b.pos.y, 1),
                round(avg_dir.x, 3),
                round(avg_dir.y, 3),
                round(b.speed, 3),
            ])

        predator_records = []
        for p in sim.predators:
            avg_dir = Vector(0.0, 0.0)
            for d in p.dir_history:
                avg_dir += d
            avg_dir = avg_dir.normalize()
            if avg_dir.length_sq() == 0:
                avg_dir = p.direction

            predator_records.append([
                round(p.pos.x, 1),
                round(p.pos.y, 1),
                round(avg_dir.x, 3),
                round(avg_dir.y, 3),
                round(p.speed, 3),
            ])

        frames.append({
            "f": f_idx,
            "boids": boid_records,
            "predators": predator_records,
        })

        sim.step(dt)

    return {
        "width": width,
        "height": height,
        "fps": fps,
        "duration": duration_seconds,
        "total_frames": total_frames,
        "preset": preset_clean,
        "boid_count": len(sim.flock),
        "predator_count": len(sim.predators),
        "obstacles": serialized_obstacles,
        "frames": frames,
    }
