"""Tests for the motion planning and the machine driver. They run against the firmware's simulated
boards through the real wrappers (firmware/xy_stage_wrapper.py, single_stepper_wrapper.py)."""
import io
import math
from pathlib import Path

import numpy as np
import pytest

from config import config_from_dict, load_config
from motion import Extrude, Pause, Prime, Retract, Wait, XYMove, motion_stats, plan_motor_moves
from pipeline import svg_to_job
from toolpath import Move
from xy_geometry import peak_share
from ufp_driver import motors_used, open_machine, plungers_used, run, simulated_machine

ROOT = Path(__file__).resolve().parent.parent
CFG = ROOT / "config" / "machine.example.yaml"
LINE = '<svg xmlns="http://www.w3.org/2000/svg" width="100mm" height="100mm" viewBox="0 0 100 100">' \
       '<path d="M10 50 L90 50 L90 20" stroke="black" fill="none"/></svg>'
FAST = 200.0    # simulation speed-up, keeps the tests short


@pytest.fixture
def cfg():
    return load_config(CFG)


def plan(cfg, svg=LINE):
    job = svg_to_job(io.StringIO(svg), cfg)
    return job, plan_motor_moves(job.events, cfg)


# --- configuration: the software must agree with the hardware it drives

def raw_config():
    import yaml
    return yaml.safe_load(CFG.read_text())


def test_home_offset_must_be_inside_the_machine_box():
    raw = raw_config()
    raw["ufp"]["home_offset"] = [-90.0, 90.0]     # the gantry stands at the homed position: it has to be a reachable point
    with pytest.raises(ValueError, match="home_offset"):
        config_from_dict(raw)


def test_per_motor_travels_are_gone_the_box_replaces_them():
    raw = raw_config()
    raw["ufp"]["travel_a"] = 480.0
    with pytest.raises(ValueError, match="travel_limits"):
        config_from_dict(raw)


def test_old_step_based_keys_are_rejected_with_a_hint():
    raw = raw_config()
    raw["ufp"]["capstan_diameter"] = 20.0
    with pytest.raises(ValueError, match="mm_per_step"):
        config_from_dict(raw)


def test_stage_limits_are_the_travel_limits_in_the_stage_frame(cfg):
    cfg.ufp.home_offset = (10.0, 20.0)
    (x_min, x_max), (y_min, y_max) = cfg.stage_limits
    t = cfg.travel_limits
    assert (x_min, x_max, y_min, y_max) == (t.x_min - 10, t.x_max - 10, t.y_min - 20, t.y_max - 20)
    assert x_min <= 0 <= x_max and y_min <= 0 <= y_max       # the homed position is inside the box


def test_the_whole_travel_box_is_usable_whatever_the_home_corner(cfg):
    """No part of the box is lost to the shape of the CoreXY belts: the planner accepts every corner."""
    t = cfg.travel_limits
    for corner in ((t.x_min, t.y_min), (t.x_max, t.y_min), (t.x_max, t.y_max), (t.x_min, t.y_max)):
        cfg.ufp.home_offset = corner
        (x_min, x_max), (y_min, y_max) = cfg.stage_limits
        assert x_min <= 0 <= x_max and y_min <= 0 <= y_max
        assert (x_max - x_min, y_max - y_min) == (t.x_max - t.x_min, t.y_max - t.y_min)


# --- planning

def test_job_starts_and_ends_at_the_home_position(cfg):
    job, steps = plan(cfg)
    moves = [s for s in steps if isinstance(s, XYMove)]
    assert (moves[-1].x, moves[-1].y) == pytest.approx(cfg.home)
    # the first travel starts from home: its length is the distance home -> first point
    first = next(e for e in job.events if isinstance(e, Move))
    assert (moves[0].x, moves[0].y) == pytest.approx((first.x, first.y))


def test_xy_moves_follow_the_toolpath(cfg):
    job, steps = plan(cfg, (ROOT / "data" / "svg" / "smiley.svg").read_text())
    moves = [(s.x, s.y) for s in steps if isinstance(s, XYMove)]
    planned = [(e.x, e.y) for e in job.events if isinstance(e, Move)] + [tuple(cfg.home)]
    assert np.allclose(moves, planned, atol=1e-9)


def test_planned_speeds_are_mm_per_second(cfg):
    _, steps = plan(cfg)
    moves = [s for s in steps if isinstance(s, XYMove)]
    assert {round(m.v, 6) for m in moves} == {cfg.print.travel_speed, cfg.print.print_speed}
    assert all(m.a == pytest.approx(cfg.ufp.accel) for m in moves)


def test_motor_limits_slow_each_move_by_its_own_motor_share(cfg):
    cfg.ufp.motor_v_max = 10.0           # a diagonal makes one motor travel up to sqrt(2) x faster than the tool
    _, steps = plan(cfg)
    here, speeds = cfg.home, []
    for s in [s for s in steps if isinstance(s, XYMove)]:
        peak = peak_share(s.x - here[0], s.y - here[1])
        assert s.v * peak <= 10.0 + 1e-9                 # no motor above its limit...
        assert s.v == pytest.approx(10.0 / peak)         # ...and every move is slowed exactly to it
        speeds.append(s.v)
        here = (s.x, s.y)
    assert max(speeds) < cfg.print.print_speed + 1e-9    # the limit really bites (a plain print move is 15 mm/s)


def test_unreachable_point_is_reported_at_planning_time(cfg):
    job = svg_to_job(io.StringIO(LINE), cfg)
    cfg.ufp.home_offset = (1000.0, 1000.0)    # the job parks at home: now outside the box, and the planner must refuse
    with pytest.raises(ValueError, match="outside machine.travel_limits"):
        plan_motor_moves(job.events, cfg)


def syringe_steps(steps):
    return [x for x in steps if isinstance(x, (Prime, Extrude, Retract))]


def test_extrusion_pushes_steps_per_mm_of_line(cfg):
    job, steps = plan(cfg)
    extrudes = [x for x in steps if isinstance(x, Extrude)]
    assert len(extrudes) == job.stats["strokes"]
    assert sum(x.steps for x in extrudes) == pytest.approx(job.stats["print_length"] * cfg.ufp.plunger_steps_per_mm)


def test_extrusion_lasts_as_long_as_the_stroke(cfg):
    cfg.ufp.plunger_steps_per_mm = 2.0
    _, steps = plan(cfg)
    i = next(k for k, x in enumerate(steps) if isinstance(x, Extrude))
    j = next(k for k in range(i, len(steps)) if isinstance(steps[k], Retract))
    stroke = sum(x.duration for x in steps[i:j] if isinstance(x, XYMove)) + sum(x.seconds for x in steps[i:j] if isinstance(x, Wait))
    assert steps[i].duration == pytest.approx(stroke, rel=1e-6)


def test_extrusion_never_overlaps_a_travel_move(cfg):
    _, steps = plan(cfg)
    running = False
    for x in steps:
        if isinstance(x, Extrude):
            running = True
        elif isinstance(x, Retract):
            running = False
        elif isinstance(x, XYMove) and running:
            assert x.v == pytest.approx(cfg.print.print_speed)    # only printing moves while the syringe extrudes
    assert not running


def test_every_stroke_is_prime_extrude_retract_by_the_same_amount(cfg):
    cfg.ufp.retract_steps = 5
    job, steps = plan(cfg)
    cycle = syringe_steps(steps)
    assert [type(x) for x in cycle] == [Prime, Extrude, Retract] * job.stats["strokes"]
    assert all(x.steps == 5 for x in cycle if not isinstance(x, Extrude))     # one number, both directions
    # prime -> extrude -> retract all happen on the same syringe, one stroke at a time
    for k in range(0, len(cycle), 3):
        assert len({x.motor for x in cycle[k:k + 3]}) == 1


def test_the_push_before_a_stroke_comes_before_its_first_printing_move(cfg):
    cfg.ufp.retract_steps = 5
    _, steps = plan(cfg)
    kinds = [type(x).__name__ for x in steps if not isinstance(x, Wait)]
    first = kinds.index("Prime")
    assert kinds[first - 1] == "XYMove"                    # the travel to the start of the stroke
    assert kinds[first:first + 3] == ["Prime", "Extrude", "XYMove"]
    assert kinds.index("Retract") > kinds.index("XYMove", first + 3) - 1


def test_zero_retract_steps_keeps_the_cycle_but_moves_nothing(cfg):
    cfg.ufp.retract_steps = 0
    job, steps = plan(cfg)
    assert [type(x) for x in syringe_steps(steps)] == [Prime, Extrude, Retract] * job.stats["strokes"]
    assert all(x.steps == 0 and x.duration == 0 for x in steps if isinstance(x, (Prime, Retract)))


def test_the_syringe_rests_retracted_and_ends_where_the_extruded_amount_puts_it(cfg):
    """Replaying the cycle: +retract, +extrude, -retract per stroke: the net movement is just the extrusion."""
    cfg.ufp.retract_steps = 7
    job, steps = plan(cfg)
    pos = 0.0
    for x in syringe_steps(steps):
        pos += x.steps if not isinstance(x, Retract) else -x.steps
        assert pos >= -1e-9
    assert pos == pytest.approx(job.stats["print_length"] * cfg.ufp.plunger_steps_per_mm)


def test_missing_plunger_board_is_reported(cfg):
    cfg.ufp.plungers.clear()
    job = svg_to_job(io.StringIO(LINE), cfg)
    with pytest.raises(ValueError, match="no plunger board"):
        plan_motor_moves(job.events, cfg)


def test_syringe_capacity_is_checked_when_planning(cfg):
    cfg.ufp.plunger_travel = 10.0
    job = svg_to_job(io.StringIO(LINE), cfg)
    with pytest.raises(ValueError, match="plunger e0 would go to"):
        plan_motor_moves(job.events, cfg)


def test_capacity_counts_the_push_of_the_cycle(cfg):
    job, _ = plan(cfg)
    need = job.stats["print_length"] * cfg.ufp.plunger_steps_per_mm
    cfg.ufp.retract_steps = 50
    cfg.ufp.plunger_travel = need + 10        # the extrusion fits; the extrusion plus the 50-step push does not
    with pytest.raises(ValueError, match="plunger e0 would go to"):
        plan_motor_moves(job.events, cfg)


def test_motion_stats(cfg):
    job, steps = plan(cfg)
    m = motion_stats(steps)
    assert m["moves"] == sum(isinstance(s, XYMove) for s in steps)
    assert m["motors"] == ["a", "b", "e0"] and motors_used(steps) == ["a", "b", "e0"]
    assert m["time"] > 0


# --- driver: the real wrappers over the firmware's simulated boards

def test_dry_run_executes_the_plan_through_the_wrappers(cfg):
    job, steps = plan(cfg)
    with simulated_machine(cfg, plungers_used(steps), time_scale=FAST) as machine:
        assert machine.stage.homed
        run(steps, machine)
        x, y = machine.xy
        assert (x, y) == pytest.approx(cfg.home, abs=2 * max(cfg.ufp.mm_per_step_pair))
        e0 = machine.syringes["e0"].position
        assert e0 == pytest.approx(job.stats["print_length"] * cfg.ufp.plunger_steps_per_mm, abs=1.0)
        assert machine.syringes.active is None          # rests retracted
        # the simulated carriages really are where the wrapper says
        sx, sy = machine.sim.xy.true_xy()
        assert math.isfinite(sx) and math.isfinite(sy)


def test_the_stage_homes_before_any_move(cfg):
    with simulated_machine(cfg, ["e0"], time_scale=FAST) as machine:
        assert machine.sim.xy.a.limit and machine.sim.xy.b.limit      # both carriages are on their switches
        assert machine.xy == pytest.approx(cfg.home, abs=1e-6)


def test_inverted_motor_still_prints_the_same_geometry(cfg):
    """Motor a wired the other way round: with invert_a the real tool follows the same path."""
    def drive(invert):
        cfg.ufp.invert_a = invert
        job, steps = plan(cfg)
        with simulated_machine(cfg, plungers_used(steps), time_scale=FAST) as machine:
            ox, oy = machine.sim.xy.true_xy()                 # where the tool really is after homing
            run(steps[:1], machine)      # the first travel: home -> start of the first stroke
            sx, sy = machine.sim.xy.true_xy()
            return (sx - ox, sy - oy), machine.xy

    real_plain, reported_plain = drive(False)
    real_inv, reported_inv = drive(True)
    assert real_inv == pytest.approx(real_plain, abs=1.0)
    assert reported_inv == pytest.approx(reported_plain, abs=1.0)
    # and the tool really moved (the check is not vacuous)
    assert math.hypot(real_inv[0], real_inv[1]) > 10


def test_wrong_motor_id_is_rejected_before_anything_moves(cfg):
    from simulated_stepper import SimulatedStepper
    from simulated_xy_stage import SimulatedXYStage
    from xy_stage_wrapper import WrongBoardError

    u = cfg.ufp
    xy = SimulatedXYStage(mm_per_step=u.mm_per_step_pair, id_a=u.xy_motors["a"].id, id_b=99)
    plunger = SimulatedStepper(start_position=0.0, motor_id=u.plungers[0].id)
    devices = {"a": xy.device_a, "b": xy.device_b, "e0": plunger.device}
    with pytest.raises(WrongBoardError, match="MOTOR_ID"):
        open_machine(cfg, ["e0"], target=devices.__getitem__)
    assert xy.a.amplitude == 0 and xy.b.amplitude == 0          # nothing left energised
    assert not xy.a._moving and not xy.b._moving


def test_wrong_plunger_board_is_rejected(cfg):
    from simulated_stepper import SimulatedStepper
    from simulated_xy_stage import SimulatedXYStage
    from xy_stage_wrapper import WrongBoardError

    u = cfg.ufp
    xy = SimulatedXYStage(mm_per_step=u.mm_per_step_pair)
    plunger = SimulatedStepper(start_position=0.0, motor_id=42)
    devices = {"a": xy.device_a, "b": xy.device_b, "e0": plunger.device}
    with pytest.raises(WrongBoardError):
        open_machine(cfg, ["e0"], target=devices.__getitem__)
    assert not xy.a._moving and not xy.b._moving                # the stage was never touched


def test_emergency_stop_halts_every_motor(cfg):
    with simulated_machine(cfg, ["e0"], time_scale=FAST) as machine:
        machine.stage.set_velocity(20, 0)
        machine.stop()
        assert machine.stage.wait(timeout=3).is_moving is False
        assert not machine.syringes["e0"].is_moving()
    assert machine.sim.xy.a.amplitude == 0 and machine.sim.xy.b.amplitude == 0   # close() cut the current


def test_dry_run_with_a_retract_cycle_follows_the_cycle_on_the_board(cfg):
    cfg.ufp.retract_steps = 12
    job, steps = plan(cfg)
    with simulated_machine(cfg, plungers_used(steps), time_scale=FAST) as machine:
        run(steps, machine)
        sim = machine.sim.syringes["e0"]
        targets = [a[0] for n, a in sim.calls if n == "set_target_position"]
        strokes = job.stats["strokes"]
        assert len(targets) == 3 * strokes                       # prime, extrude, retract per stroke
        rest = [targets[3 * k + 2] for k in range(strokes)]      # position after each retraction
        starts = [0.0] + rest[:-1]
        for k in range(strokes):                                 # each push starts from where the last retraction ended
            assert targets[3 * k] == pytest.approx(starts[k] + 12)
            assert targets[3 * k + 2] == pytest.approx(targets[3 * k + 1] - 12)
        assert rest[-1] == pytest.approx(job.stats["print_length"] * cfg.ufp.plunger_steps_per_mm, abs=0.01)


def test_the_syringe_is_not_commanded_before_the_stage_has_homed(cfg):
    job, steps = plan(cfg)
    with simulated_machine(cfg, plungers_used(steps), time_scale=FAST) as machine:
        assert machine.sim.xy.a.limit and machine.sim.xy.b.limit
        assert not [c for c in machine.sim.syringes["e0"].calls if c[0] == "set_target_position"]


# --- three colours: each with its own board address

def test_three_colours_have_three_distinct_boards(cfg):
    u = cfg.ufp
    assert sorted(u.plungers) == [0, 1, 2]
    assert len({b.port for b in u.plungers.values()}) == 3 and len({b.id for b in u.plungers.values()}) == 3


def test_two_colours_cannot_share_a_port_unless_it_is_the_same_board():
    raw = raw_config()
    raw["ufp"]["plungers"][1]["port"] = raw["ufp"]["plungers"][0]["port"]       # same port, different MOTOR_ID
    with pytest.raises(ValueError, match="both on port"):
        config_from_dict(raw)
    raw["ufp"]["plungers"][1]["id"] = raw["ufp"]["plungers"][0]["id"]           # the same board on purpose
    config_from_dict(raw)


def test_a_plunger_cannot_share_a_port_with_an_xy_motor():
    raw = raw_config()
    raw["ufp"]["plungers"][0]["port"] = raw["ufp"]["xy_motors"]["a"]["port"]
    with pytest.raises(ValueError, match="both on port"):
        config_from_dict(raw)


def test_prime_steps_is_gone(cfg):
    raw = raw_config()
    raw["ufp"]["prime_steps"] = 5
    with pytest.raises(ValueError, match="retract_steps"):
        config_from_dict(raw)


# --- the stage may use the whole box: straight horizontal and vertical lines were refused before

def test_horizontal_and_vertical_lines_across_the_whole_box(cfg):
    """With the homed position in a corner of the box (the example config), one motor has to go past its
    switch reference to reach the far side: the old per-motor travel refused exactly these lines."""
    t = cfg.travel_limits
    with simulated_machine(cfg, ["e0"], time_scale=400.0) as machine:
        ox, oy = cfg.home
        for x, y in ((t.x_max, oy), (t.x_max, t.y_max), (t.x_min, t.y_max), (t.x_min, oy),     # round the box
                     (t.x_max, t.y_max), (t.x_max, t.y_min), (ox, oy)):                         # and the diagonal
            machine.move_xy(XYMove(x, y, 400.0, 3000.0, 0.0))
            assert machine.xy == pytest.approx((x, y), abs=1.0)
            sx, sy = machine.sim.xy.true_xy()
            assert math.isfinite(sx) and math.isfinite(sy)


def test_a_move_outside_the_box_is_refused_before_any_motor_moves(cfg):
    t = cfg.travel_limits
    with simulated_machine(cfg, ["e0"], time_scale=400.0) as machine:
        before = machine.sim.xy.true_xy()
        for x, y in ((t.x_max + 5, t.y_min), (t.x_min, t.y_max + 5), (t.x_min - 5, t.y_min)):
            with pytest.raises(ValueError, match="leaves the workspace"):
                machine.move_xy(XYMove(x, y, 100.0, 1000.0, 0.0))
        assert machine.sim.xy.true_xy() == pytest.approx(before)


def test_every_motor_range_is_derived_from_the_box(cfg):
    from xy_geometry import motor_ranges
    (x_min, x_max), (y_min, y_max) = cfg.stage_limits
    (a_min, a_max), (b_min, b_max) = motor_ranges(x_min, x_max, y_min, y_max)
    with simulated_machine(cfg, ["e0"], time_scale=400.0) as machine:
        a, b = machine.stage._motors
        assert (a.z_min, a.z_max, a.z_switch) == pytest.approx((a_min, a_max, 0.0))
        assert (b.z_min, b.z_max, b.z_switch) == pytest.approx((b_min, b_max, 0.0))
        assert b_min < 0 < b_max       # with the homed corner at (0, 0): b = x - y must go below its switch for y > x
