"""Colour -> nozzle assignment.
Picks the nozzle whose configured `color` is closest to the SVG colour (not exact match).
Only nozzles listed in print.color_order are candidates, so `color_order: [0]` prints everything with nozzle 0.

Distance: "redmean" weighted RGB (one line approximation)
"""
import math

from matplotlib.colors import to_rgb

from config import MachineConfig
from geometry import Polyline


def color_distance(c1: str, c2: str) -> float: # redmean weighted RGB
    (r1, g1, b1), (r2, g2, b2) = ([255 * v for v in to_rgb(c)] for c in (c1, c2))
    rm = (r1 + r2) / 2
    return math.sqrt((2 + rm / 256) * (r1 - r2) ** 2 + 4 * (g1 - g2) ** 2 + (2 + (255 - rm) / 256) * (b1 - b2) ** 2)


def nearest_nozzle(color: str | None, cfg: MachineConfig) -> int:
    """Nozzle id for one SVG color (only select nozzles in color_order)"""
    if color is None:
        return cfg.print.color_order[0]
    return min(cfg.print.color_order, key=lambda n: color_distance(color, cfg.nozzles[n].color))


def assign_nozzles(paths: list[Polyline], cfg: MachineConfig) -> dict[str | None, int]:
    mapping: dict[str | None, int] = {}
    for p in paths:
        if p.color not in mapping:
            mapping[p.color] = nearest_nozzle(p.color, cfg)
        p.nozzle = mapping[p.color]
    return mapping
