"""Machine configuration: loaded from YAML. Refer to config/machine.example.yaml for more details."""
from dataclasses import dataclass, field
from pathlib import Path

import yaml # will require install of pyyaml, I will prepare a requirements.txt file for this project
# I can also work with firmware team to get a single requirements.txt file for this project

import firmware_link  # noqa: F401  (puts ../firmware on sys.path)


@dataclass
class Rect: # self explained rectangle class
    x_min: float
    x_max: float
    y_min: float
    y_max: float

    def contains(self, x, y, tol=1e-6): # math to check if a point is within the rectangle
        return (self.x_min - tol <= x <= self.x_max + tol) and (self.y_min - tol <= y <= self.y_max + tol)
    
    def shifted(self, dx, dy) -> "Rect":
        return Rect(self.x_min + dx, self.x_max + dx, self.y_min + dy, self.y_max + dy)

    def intersect(self, other: "Rect") -> "Rect":
        """handle overlap of two rectangles"""
        return Rect(max(self.x_min, other.x_min), min(self.x_max, other.x_max),
                    max(self.y_min, other.y_min), min(self.y_max, other.y_max))


@dataclass
class Nozzle:
    id: int
    name: str
    color: str                         # hex, used for preview, updated to work with multiple colors
    offset: tuple[float, float]        # nozzle tip relative to reference point, mm


@dataclass
class PrintSettings: # default values for print settings
    line_width: float = 3.0
    print_speed: float = 15.0          # mm/s
    travel_speed: float = 60.0         # mm/s
    extrude_start_delay: float = 0.3   # s
    extrude_stop_delay: float = 0.0    # s
    curve_tolerance: float = 0.2       # max deviation from true curve, mm
    min_path_length: float = 2.0       # mm
    color_order: list[int] = field(default_factory=list)
    pause_between_colors: bool = False # real print waits for Enter before each new colour


@dataclass
class DesignSettings:
    fit_to_print_area: bool = True
    margin: float = 5.0
    max_size: float | None = None


@dataclass
class MotorBoard: # to interact with the UFP stepper boards, will require manual testing
    port: str                          # serial port of the UFP stepper board
    id: int | None = None              # expected MOTOR_ID; checked on connect


@dataclass
class UfpSettings: # refer to config/machine.example.yaml for more details
    """UFP stepper boards (one per motor), driven through firmware/xy_stage_wrapper.py and
    firmware/single_stepper_wrapper.py. Everything is in mm (the wrappers convert to steps), except
    the plungers, whose axis is in steps. Stage frame: (0, 0) = the homed position, both XY motors on their
    limit switches. The usable region is machine.travel_limits (an x / y box), see MachineConfig.stage_limits."""
    xy_motors: dict[str, MotorBoard]   # the two CoreXY motors, 'a' and 'b'
    plungers: dict[int, MotorBoard]    # nozzle id -> its syringe plunger board
    home_offset: tuple[float, float]   # MACHINE coordinates of the homed position (stage 0, 0), mm. Must lie inside machine.travel_limits
    current: float = 0.2               # coil current, 0-1 of full scale
    mm_per_step: float | tuple[float, float] = 0.31416  # belt mm per full step (pi * capstan diameter / steps per rev); one number or (a, b)
    invert_a: bool = False             # flip a motor's direction if backwards
    invert_b: bool = False
    accel: float = 300.0               # XY acceleration along the path, mm/s^2
    emergency_decel: float = 5000.0    # deceleration of stop() on Ctrl+C / errors, mm/s^2
    motor_v_max: float | None = None   # per-motor speed limit, mm/s of belt (a diagonal needs sqrt(2) x tool speed)
    motor_a_max: float | None = None   # per-motor acceleration limit, mm/s^2
    homing_timeout: float | None = None  # s; None = derived by the wrapper
    plunger_steps_per_mm: float = 1.0  # plunger steps per mm of printed line, placeholder value here
    plunger_travel: float = 100000.0   # usable plunger stroke, steps (the syringe's capacity)
    retract_steps: float = 0.0         # pull-back after every stroke, and the same push before the next one
    plunger_speed: float = 200.0       # steps/s for prime / retract
    plunger_accel: float = 1000.0      # steps/s^2 for prime / retract and flow

    def __post_init__(self):
        self.home_offset = (float(self.home_offset[0]), float(self.home_offset[1]))
        if isinstance(self.mm_per_step, (list, tuple)):
            self.mm_per_step = (float(self.mm_per_step[0]), float(self.mm_per_step[1]))
        positive = {"accel": self.accel,
                    "emergency_decel": self.emergency_decel, "plunger_travel": self.plunger_travel,
                    "plunger_speed": self.plunger_speed, "plunger_accel": self.plunger_accel,
                    **dict(zip(("mm_per_step[a]", "mm_per_step[b]"), self.mm_per_step_pair))}
        for name, value in positive.items():
            if not value > 0:
                raise ValueError(f"ufp.{name} must be > 0, got {value}")
        if not 0 <= self.current <= 1:
            raise ValueError(f"ufp.current must be in 0..1, got {self.current}")
        if min(self.plunger_steps_per_mm, self.retract_steps) < 0:
            raise ValueError("ufp.plunger_steps_per_mm and retract_steps must be >= 0")
        if self.retract_steps > self.plunger_travel:
            raise ValueError(f"ufp.retract_steps ({self.retract_steps}) is longer than the plunger stroke "
                             f"(plunger_travel {self.plunger_travel})")

    @property
    def mm_per_step_pair(self) -> tuple[float, float]:
        m = self.mm_per_step
        return tuple(m) if isinstance(m, tuple) else (m, m)


@dataclass
class MachineConfig:
    travel_limits: Rect
    print_area: Rect
    nozzles: dict[int, Nozzle]
    print: PrintSettings
    design: DesignSettings
    ufp: UfpSettings | None = None     # only needed to drive the UFP boards

    @property
    def home(self) -> tuple[float, float]:
        """Machine position of the gantry when a job starts and ends (where the homed stage sits)."""
        return self.ufp.home_offset if self.ufp else (0.0, 0.0)

    @property
    def stage_limits(self) -> tuple[tuple[float, float], tuple[float, float]]:
        """(x_limits, y_limits) for the XY wrapper: machine.travel_limits in the stage frame, where the
        homed position is (0, 0). The motors' own ranges follow from this box (xy_geometry.motor_ranges)."""
        ox, oy = self.home
        t = self.travel_limits
        return (t.x_min - ox, t.x_max - ox), (t.y_min - oy, t.y_max - oy)

    def check_home(self) -> None:
        """The gantry sits at ufp.home_offset after homing, so that point has to be inside the box."""
        if self.ufp and not self.travel_limits.contains(*self.ufp.home_offset):
            t, h = self.travel_limits, self.ufp.home_offset
            raise ValueError(f"ufp.home_offset ({h[0]:g}, {h[1]:g}) is outside machine.travel_limits "
                             f"(x {t.x_min:g}..{t.x_max:g}, y {t.y_min:g}..{t.y_max:g}): the gantry stands there "
                             "after homing, so it has to be a point the machine can be at")

    def to_machine(self, nozzle_id, x, y): # math to convert bed point to gantry position
        """Bed point (where batter lands) -> gantry position that puts the nozzle there."""
        ox, oy = self.nozzles[nozzle_id].offset
        return x - ox, y - oy

    def to_bed(self, nozzle_id, x, y):
        ox, oy = self.nozzles[nozzle_id].offset
        return x + ox, y + oy

    def reachable_area(self, nozzle_ids) -> Rect:
        """Part of print_area (bed coordinates) that every listed nozzle can reach.
        This is to account for the nozzle offsets"""
        area = self.print_area
        for n in nozzle_ids:
            area = area.intersect(self.travel_limits.shifted(*self.nozzles[n].offset))
        if area.x_min >= area.x_max or area.y_min >= area.y_max:
            raise ValueError(f"No part of print_area is reachable by all nozzles {sorted(nozzle_ids)}: "
                             "check the nozzle offsets against machine.travel_limits")
        return area

def load_config(path) -> MachineConfig: # load the config from the yaml file
    raw = yaml.safe_load(Path(path).read_text())
    return config_from_dict(raw)


def config_from_dict(raw: dict) -> MachineConfig:
    nozzles = {}
    for n in raw["nozzles"]:
        nozzles[n["id"]] = Nozzle(id=n["id"], name=n.get("name", str(n["id"])),
                                  color=n.get("color", "#000000"), offset=tuple(n.get("offset", (0, 0))))
    pr = PrintSettings(**raw.get("print", {}))
    if not pr.color_order:
        pr.color_order = sorted(nozzles)
    unknown = set(pr.color_order) - set(nozzles)
    if unknown:
        raise ValueError(f"color_order refers to unknown nozzle ids: {sorted(unknown)}")
    cfg = MachineConfig(
        travel_limits=Rect(**raw["machine"]["travel_limits"]),
        print_area=Rect(**raw["print_area"]),
        nozzles=nozzles,
        print=pr,
        design=DesignSettings(**raw.get("design", {})),
        ufp=_ufp_from_dict(raw["ufp"], nozzles) if raw.get("ufp") else None,
    )
    cfg.check_home()
    return cfg


def _check_board_addresses(xy: dict, plungers: dict) -> None:
    """Every board is one port. Two colours may share a plunger board on purpose (same port AND same
    MOTOR_ID, syringe swapped by hand, see print.pause_between_colors); anything else on one port is a mistake."""
    seen: dict[str, tuple[str, MotorBoard]] = {}
    for label, board in [(f"xy motor {n}", b) for n, b in xy.items()] + [(f"plunger of nozzle {n}", b) for n, b in plungers.items()]:
        other = seen.get(board.port)
        if other is None:
            seen[board.port] = (label, board)
        elif not (label.startswith("plunger") and other[0].startswith("plunger") and other[1].id == board.id):
            raise ValueError(f"{label} and {other[0]} are both on port {board.port}: "
                             "each board needs its own port (only plungers with the same MOTOR_ID may share one)")


def _ufp_from_dict(raw: dict, nozzles: dict) -> UfpSettings:
    raw = dict(raw)
    xy = {name: MotorBoard(**b) for name, b in raw.pop("xy_motors").items()}
    if set(xy) != {"a", "b"}:
        raise ValueError(f"ufp.xy_motors needs exactly 'a' and 'b', got {sorted(xy)}")
    plungers = {int(n): MotorBoard(**b) for n, b in raw.pop("plungers", {}).items()}
    unknown = set(plungers) - set(nozzles)
    if unknown:
        raise ValueError(f"ufp.plungers refers to unknown nozzle ids: {sorted(unknown)}")
    _check_board_addresses(xy, plungers)
    removed = {"steps_per_rev": "use mm_per_step (= pi * capstan diameter / steps per rev)",
               "capstan_diameter": "use mm_per_step (= pi * capstan diameter / steps per rev)",
               "stop_accel": "renamed emergency_decel, now in mm/s^2 (was steps/s^2)",
               "prime_steps": "removed: the push before a stroke is always retract_steps, the amount pulled back after the last one",
               "travel_a": "removed: the usable region is machine.travel_limits (x / y), each motor's range follows from it",
               "travel_b": "removed: the usable region is machine.travel_limits (x / y), each motor's range follows from it"}
    stale = [f"{k}: {why}" for k, why in removed.items() if k in raw]
    if stale:
        raise ValueError("ufp config keys that no longer exist: " + "; ".join(stale))
    if "home_offset" not in raw:
        raise ValueError("ufp config is missing home_offset: the machine position (x, y) of the gantry when homed")
    return UfpSettings(xy_motors=xy, plungers=plungers, **raw)


# no longer needed since we are working with ufp
# @dataclass
# class GcodeSettings:
#     header: list[str] = field(default_factory=lambda: ["G21", "G90"])
#     footer: list[str] = field(default_factory=list)
#     select_nozzle: str = "; SELECT_NOZZLE {nozzle}"
#     extrude_on: str = "; EXTRUDE_ON {nozzle}"
#     extrude_off: str = "; EXTRUDE_OFF {nozzle}"
#     dwell: str = "G4 P{seconds:.2f}"

