# combat.py : maths pures (hitbox, normalisation, distance segment)

import math


def circle_overlap(ax, ay, ar, bx, by, br):
    # comparer les carres evite math.sqrt
    dx = ax - bx
    dy = ay - by
    dist_sq = dx * dx + dy * dy
    radii = ar + br
    return dist_sq <= radii * radii


def normalize(dx, dy):
    mag_sq = dx * dx + dy * dy
    if mag_sq == 0.0:
        return 0.0, 0.0
    mag = math.sqrt(mag_sq)
    return dx / mag, dy / mag


def segment_point_dist(px, py, ax, ay, bx, by):
    # distance min entre le point P et le segment [AB], utilise pour la charge de Kael
    dx, dy = bx - ax, by - ay

    if dx == 0.0 and dy == 0.0:
        # A == B, le segment est un point
        return math.sqrt((px - ax) ** 2 + (py - ay) ** 2)

    # projection de P sur AB, clamp entre 0 et 1
    t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy)))
    cx, cy = ax + t * dx, ay + t * dy
    return math.sqrt((px - cx) ** 2 + (py - cy) ** 2)
