"""Motion planning: print events -> steps for the firmware wrappers (firmware/xy_stage_wrapper.py,
firmware/syringe_wrapper.py).

Pure functions, no hardware. See ufp_driver.py to run the result on a machine.
XY is in MILLIMETRES (machine coordinates, speeds in mm/s, accelerations in mm/s^2); the wrapper does
the conversion to motor steps and the CoreXY transform. Syringe plungers are in steps.

Three colours = three nozzles, each with its own syringe board (ufp.plungers: nozzle id -> port + MOTOR_ID).
They are used one at a time, and every stroke is the same cycle on that nozzle's syringe:

    Prime    push forward by ufp.retract_steps (takes up the slack the previous retraction made)
    Extrude  push for the stroke, ONE move spread over the stroke's planned time (dwell + XY moves)
    Retract  pull back by ufp.retract_steps (anti-drip); waits for the extrusion to finish first

So a stroke always starts with exactly the push that the previous one's retraction pulled back, and the
plunger rests at (start + everything extruded). The XY moves of the stroke run while Extrude does, so the
flow is even in time, not locked to the position along the line (the XY stage stops at every vertex).
A colour change needs no motion: the syringe is already retracted, the next one just primes.
"""
import math
from dataclasses import dataclass

import firmware_link  # noqa: F401  (puts ../firmware on sys.path)
from config import MachineConfig
from motion_profile import flow_profile, trapezoid_time
from toolpath import Dwell, Event, ExtrudeOff, ExtrudeOn, Move, SelectNozzle
from xy_geometry import apply_motor_limits, peak_share

EPS = 1e-9


@dataclass
class XYMove:
    """Straight line of the gantry to (x, y), MACHINE coordinates in mm. Waits until it is done."""
    x: float
    y: float
    v: float                      # mm/s along the line, after the per-motor limits
    a: float                      # mm/s^2 along the line, after the per-motor limits
    duration: float               # s, planned


@dataclass
class Prime:
    """Push the syringe `steps` forward before a stroke. Waits until it is done."""
    motor: str                    # "e<N>", see plunger_motor
    steps: float
    duration: float               # s, planned


@dataclass
class Extrude:
    """Push `steps` for the stroke, paced to take `duration` s. Does NOT wait: the stroke's XY moves
    run meanwhile, and the Retract after the stroke waits for it."""
    motor: str
    steps: float
    duration: float               # s, the pacing the plunger is asked for


@dataclass
class Retract:
    """Pull the syringe back `steps` after the stroke (once the extrusion has finished). Waits."""
    motor: str
    steps: float
    duration: float               # s, planned for the pull-back itself


@dataclass
class Wait:
    seconds: float


@dataclass
class Pause:
    message: str                  # shown to the operator; the real print waits for Enter


Step = XYMove | Prime | Extrude | Retract | Wait | Pause


def plunger(nozzle: int) -> str: # motor name of a nozzle's plunger
    return f"e{nozzle}"


def plunger_motor(u, nozzle: int) -> str:
    """Motor name used for a nozzle's plunger. Nozzles whose boards share a port share the motor."""
    port = u.plungers[nozzle].port
    return plunger(min(n for n, b in u.plungers.items() if b.port == port))


def plan_motor_moves(events: list[Event], cfg: MachineConfig) -> list[Step]:
    u = cfg.ufp
    if u is None:
        raise ValueError("config has no 'ufp' section") # if no ufp section, we have a problem
    pos: dict[str, float] = {}                    # resting plunger positions (retracted), steps
    xy = cfg.home                                 # the job starts where the homed stage sits
    nozzle = None
    primed = None                                 # (motor, extruded steps) between ExtrudeOn and ExtrudeOff
    steps: list[Step] = []
    retract = u.retract_steps
    retract_time = trapezoid_time(retract, u.plunger_speed, u.plunger_accel)

    def segment(frm, to, speed):
        """(length, v, a, duration) of a line, with the per-motor limits applied."""
        dx, dy = to[0] - frm[0], to[1] - frm[1]
        length = math.hypot(dx, dy)
        if length < EPS:
            return 0.0, speed, u.accel, 0.0
        v, a = apply_motor_limits(speed, u.accel, peak_share(dx, dy), u.motor_v_max, u.motor_a_max)
        return length, v, a, trapezoid_time(length, v, a)

    def move_xy(x, y, speed):
        nonlocal xy
        length, v, a, t = segment(xy, (x, y), speed)
        if length == 0.0:
            return
        if not cfg.travel_limits.contains(x, y):
            t = cfg.travel_limits
            raise ValueError(f"({x:.2f}, {y:.2f}) is outside machine.travel_limits "
                             f"(x {t.x_min:g}..{t.x_max:g}, y {t.y_min:g}..{t.y_max:g})")
        steps.append(XYMove(x, y, v, a, t))
        xy = (x, y)

    def stroke_ahead(i):
        """(printed length mm, seconds) of the stroke announced by the ExtrudeOn at events[i]:
        the start dwell and every printing move that follows."""
        here, length, t, j = xy, 0.0, 0.0, i + 1
        while j < len(events) and (isinstance(events[j], Dwell) or (isinstance(events[j], Move) and events[j].printing)):
            if isinstance(events[j], Dwell):
                t += events[j].seconds
            else:
                ln, _, _, dt = segment(here, (events[j].x, events[j].y), events[j].speed)
                length, t, here = length + ln, t + dt, (events[j].x, events[j].y)
            j += 1
        return length, t

    def begin_stroke(i):
        nonlocal primed
        e = plunger_motor(u, nozzle)
        length, t = stroke_ahead(i)
        delta = length * u.plunger_steps_per_mm
        top = pos.get(e, 0.0) + retract + delta   # the plunger's highest position in this stroke
        if top > u.plunger_travel + EPS:
            raise ValueError(f"plunger {e} would go to {top:.0f} steps, outside its stroke "
                             f"0..{u.plunger_travel:g} (ufp.plunger_travel): refill the syringe or "
                             "check plunger_steps_per_mm / retract_steps")
        steps.append(Prime(e, retract, retract_time))      # always the full cycle, even for 0 steps
        if delta >= EPS:
            steps.append(Extrude(e, delta, t))
        primed = (e, delta)

    def end_stroke():
        nonlocal primed
        e, delta = primed
        steps.append(Retract(e, retract, retract_time))
        pos[e] = pos.get(e, 0.0) + delta          # rests retracted, delta further than it started
        primed = None

    for i, ev in enumerate(events):
        if isinstance(ev, Move):
            move_xy(ev.x, ev.y, ev.speed)
        elif isinstance(ev, SelectNozzle):
            if ev.nozzle not in u.plungers: # if the nozzle has no plunger board, we have a problem
                raise ValueError(f"nozzle {ev.nozzle} has no plunger board in ufp.plungers")
            if primed is not None:
                raise ValueError(f"nozzle changed in the middle of a stroke (nozzle {nozzle})")
            if nozzle is not None and ev.nozzle != nozzle and cfg.print.pause_between_colors:
                old, new = cfg.nozzles[nozzle], cfg.nozzles[ev.nozzle]
                steps.append(Pause(f"Colour change: nozzle {old.id} ({old.name}) done, "
                                   f"next nozzle {new.id} ({new.name}). Get it ready."))
            nozzle = ev.nozzle
        elif isinstance(ev, ExtrudeOn):
            if primed is not None:
                raise ValueError("ExtrudeOn while a stroke is running")
            begin_stroke(i)
        elif isinstance(ev, ExtrudeOff):
            if primed is None:
                raise ValueError("ExtrudeOff without ExtrudeOn")
            end_stroke()
        elif isinstance(ev, Dwell):
            steps.append(Wait(ev.seconds))
    if primed is not None:
        end_stroke()
    move_xy(*cfg.home, cfg.print.travel_speed)    # park at the home position, ready for the next job
    return steps


def motion_stats(steps: list[Step]) -> dict:
    moves = [s for s in steps if isinstance(s, XYMove)]
    syringes = {s.motor for s in steps if isinstance(s, (Prime, Extrude, Retract))}
    return {
        "moves": len(moves),
        # Extrude overlaps the stroke's XY moves, so only prime / retract add time
        "time": (sum(s.duration for s in moves) + sum(s.seconds for s in steps if isinstance(s, Wait))
                 + sum(s.duration for s in steps if isinstance(s, (Prime, Retract)))),
        "motors": ["a", "b"] + sorted(syringes),
        "pauses": sum(isinstance(s, Pause) for s in steps),
    }
