"""Uploadable Planner v1 example: circular-obstacle detour."""

import math

from synforge_core import Action, PlanContext, Planner


class SubmittedPlanner(Planner):
    margin = 1.0
    outward_weight = 0.5

    def plan(self, ctx: PlanContext) -> Action:
        delta_x = ctx.target_x - ctx.x
        delta_y = ctx.target_y - ctx.y
        distance = math.hypot(delta_x, delta_y)
        if distance < 1e-12:
            return Action(0.0, 0.0)
        target_x, target_y = delta_x / distance, delta_y / distance
        nearest = min(
            ctx.obstacles,
            key=lambda obstacle: math.hypot(
                ctx.x - obstacle.x, ctx.y - obstacle.y
            ) - obstacle.radius,
            default=None,
        )
        if nearest is not None:
            obstacle_x, obstacle_y = ctx.x - nearest.x, ctx.y - nearest.y
            obstacle_distance = math.hypot(obstacle_x, obstacle_y)
            if 1e-12 < obstacle_distance < nearest.radius + self.margin:
                normal_x, normal_y = (
                    obstacle_x / obstacle_distance,
                    obstacle_y / obstacle_distance,
                )
                tangent_a, tangent_b = (-normal_y, normal_x), (normal_y, -normal_x)
                tangent_x, tangent_y = max(
                    (tangent_a, tangent_b),
                    key=lambda tangent: tangent[0] * target_x + tangent[1] * target_y,
                )
                velocity_x = tangent_x + self.outward_weight * normal_x
                velocity_y = tangent_y + self.outward_weight * normal_y
                magnitude = math.hypot(velocity_x, velocity_y)
                return Action(
                    ctx.speed * velocity_x / magnitude,
                    ctx.speed * velocity_y / magnitude,
                )
        return Action(ctx.speed * target_x, ctx.speed * target_y)