"""Toolpath planning: polylines -> hardware-independent print events.
serves as the bridge between the design and the hardware
Move coordinates are MACHINE coordinates (gantry reference point), no offsets are needed here.
"""
from dataclasses import dataclass

import numpy as np

from config import MachineConfig
from geometry import Polyline


@dataclass # all class here are self-explanatory
class Move:
    x: float
    y: float
    speed: float        # mm/s
    printing: bool      # True while batter is flowing


@dataclass
class SelectNozzle:
    nozzle: int


@dataclass
class ExtrudeOn:
    nozzle: int


@dataclass
class ExtrudeOff:
    nozzle: int


@dataclass
class Dwell:
    seconds: float


Event = Move | SelectNozzle | ExtrudeOn | ExtrudeOff | Dwell # event list is the contract between planning and every consumer 


class OutOfBoundsError(ValueError):
    pass


def plan(paths: list[Polyline], cfg: MachineConfig) -> list[Event]:
    """Group paths by nozzle (in color_order), order them to reduce travel, emit events.
    drop the paths shorter than min_path_length
    checks path illegal bounds
    order nozzles path
    11/15 now uses gantry to track position after color change
    """
    pr = cfg.print
    paths = [p for p in paths if p.length() >= pr.min_path_length]
    _check_print_area(paths, cfg)

    events: list[Event] = []
    gantry = cfg.home     # machine position; a job starts where the homed stage sits (ufp.home_offset)
    for nozzle in pr.color_order:
        layer = [p for p in paths if p.nozzle == nozzle]
        if not layer:
            continue
        events.append(SelectNozzle(nozzle))
        head = cfg.to_bed(nozzle, *gantry)   # where this nozzle's tip is right now, bed coordinates
        for p in order_paths(layer, start=head):
            pts = np.vstack([p.points, p.points[:1]]) if p.closed else p.points
            events.append(_move(cfg, nozzle, pts[0], pr.travel_speed, False))
            events.append(ExtrudeOn(nozzle))
            if pr.extrude_start_delay > 0:
                events.append(Dwell(pr.extrude_start_delay))
            events.extend(_move(cfg, nozzle, pt, pr.print_speed, True) for pt in pts[1:])
            events.append(ExtrudeOff(nozzle))
            if pr.extrude_stop_delay > 0:
                events.append(Dwell(pr.extrude_stop_delay))
            head = pts[-1]
        gantry = cfg.to_machine(nozzle, *head)   # the next nozzle starts from here
    return events


def order_paths(paths: list[Polyline], start=None) -> list[Polyline]:
    """Greedy nearest-neighbour ordering. Open paths may be reversed but should not matter;"""
    remaining = list(paths)
    pos = np.asarray(start) if start is not None else remaining[0].points[0]
    ordered = []
    while remaining:
        best_i, best_d, best_path = 0, np.inf, None # initialize the best index, distance, and path
        for i, p in enumerate(remaining):
            if p.closed:
                d2 = ((p.points - pos) ** 2).sum(axis=1)
                k = int(d2.argmin())
                cand = Polyline(np.roll(p.points, -k, axis=0), True, p.color, p.nozzle), d2[k]
            else:
                ds, de = ((p.points[0] - pos) ** 2).sum(), ((p.points[-1] - pos) ** 2).sum()
                cand = (p, ds) if ds <= de else (p.reversed(), de)
            if cand[1] < best_d:
                best_i, best_d, best_path = i, cand[1], cand[0]
        remaining.pop(best_i)
        ordered.append(best_path)
        pos = best_path.points[0] if best_path.closed else best_path.points[-1]
    return ordered


def _move(cfg, nozzle, bed_pt, speed, printing): # math to convert bed point to gantry position
    x, y = cfg.to_machine(nozzle, float(bed_pt[0]), float(bed_pt[1])) # convert bed point to gantry position
    if not cfg.travel_limits.contains(x, y): # if the gantry position is outside the travel limits, raise an error
        raise OutOfBoundsError(
            f"Nozzle {nozzle} cannot reach bed point ({bed_pt[0]:.1f}, {bed_pt[1]:.1f}): gantry would need "
            f"({x:.1f}, {y:.1f}), outside travel limits. Check print_area vs. nozzle offset.")
    return Move(x, y, speed, printing) # return the move event


def _check_print_area(paths, cfg):
    a = cfg.print_area # print area is the area where the design can be printed
    for p in paths:
        lo, hi = p.points.min(axis=0), p.points.max(axis=0)
        if not (a.contains(*lo) and a.contains(*hi)):
            raise OutOfBoundsError(f"Path with bounds {lo.round(1)}-{hi.round(1)} leaves the print area")
