"""Phase 2: colour -> nozzle assignment, offsets, reach, and multi-plunger motion."""
from pathlib import Path

import numpy as np
import pytest

from colors import nearest_nozzle
from config import MotorBoard, load_config
from motion import Extrude, Pause, Prime, Retract, plan_motor_moves
from pipeline import svg_to_job
from preview import render, trace
from toolpath import Move, SelectNozzle
from ufp_driver import motors_used, plungers_used, run, simulated_machine

ROOT = Path(__file__).resolve().parent.parent
CFG = ROOT / "config" / "machine.example.yaml"
TWO = ROOT / "data" / "svg" / "two_color.svg"


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


def test_nearest_colour_picks_the_nozzle(cfg):
    # config: 0 dark "#5a3216", 1 medium "#b07a3a", 2 light "#e8c27a"
    assert nearest_nozzle("#000000", cfg) == 0
    assert nearest_nozzle("#a0703a", cfg) == 1
    assert nearest_nozzle("#ffe0a0", cfg) == 2
    assert nearest_nozzle(None, cfg) == cfg.print.color_order[0]
    cfg.print.color_order = [2]                      # only nozzle 2 enabled: everything goes there
    assert nearest_nozzle("#000000", cfg) == 2


def test_two_colour_svg_gives_one_toolpath_per_nozzle(cfg):
    job = svg_to_job(TWO, cfg)
    assert job.color_map == {"#f2c14e": 2, "#222222": 0}
    # events: nozzle 0 first (color_order), then nozzle 2, each selected exactly once
    assert [e.nozzle for e in job.events if isinstance(e, SelectNozzle)] == [0, 2]
    strokes, _ = trace(job.events, cfg)
    assert sorted({n for n, _ in strokes}) == [0, 2]
    by = job.stats["print_length_by_nozzle"]
    assert by[0] + by[2] == pytest.approx(job.stats["print_length"])


def test_offsets_are_compensated_per_nozzle(cfg):
    job = svg_to_job(TWO, cfg)
    nozzle = None
    for e in job.events:
        if isinstance(e, SelectNozzle):
            nozzle = e.nozzle
        elif isinstance(e, Move):
            assert cfg.travel_limits.contains(e.x, e.y)
            if e.printing:   # batter lands at gantry + offset, which must be on a path of that nozzle
                bed = np.array(cfg.to_bed(nozzle, e.x, e.y))
                d = min(np.linalg.norm(p.points - bed, axis=1).min() for p in job.paths if p.nozzle == nozzle)
                assert d < 1e-6


def test_design_is_placed_where_all_used_nozzles_reach(cfg):
    cfg.nozzles[2].offset = (-80.0, 0.0)     # nozzle 2 can't reach bed x > 300 - 80 = 220
    job = svg_to_job(TWO, cfg)
    assert max(p.points[:, 0].max() for p in job.paths) <= 220 + 1e-6
    assert all(cfg.travel_limits.contains(e.x, e.y) for e in job.events if isinstance(e, Move))


def test_each_nozzle_drives_its_own_plunger(cfg):
    cfg.ufp.retract_steps = 9
    job = svg_to_job(TWO, cfg)
    steps = plan_motor_moves(job.events, cfg)
    by = job.stats["print_length_by_nozzle"]
    spm = cfg.ufp.plunger_steps_per_mm
    assert motors_used(steps) == ["a", "b", "e0", "e2"]
    pushed = {}
    for s in steps:
        if isinstance(s, Extrude):
            pushed[s.motor] = pushed.get(s.motor, 0.0) + s.steps
    assert pushed["e0"] == pytest.approx(by[0] * spm)
    assert pushed["e2"] == pytest.approx(by[2] * spm)
    assert not any(isinstance(s, Pause) for s in steps)   # pause is off by default
    with simulated_machine(cfg, plungers_used(steps), time_scale=400.0) as machine:
        run(steps, machine)
        assert machine.syringes["e0"].position == pytest.approx(by[0] * spm, abs=1.0)
        assert machine.syringes["e2"].position == pytest.approx(by[2] * spm, abs=1.0)
        assert machine.syringes["e0"].motor.coil_current > 0 and machine.syringes.active is None


def test_colours_are_used_one_at_a_time(cfg):
    """A syringe is fully retracted before the next colour starts: no two are ever primed together."""
    cfg.ufp.retract_steps = 9
    job = svg_to_job(TWO, cfg)
    steps = plan_motor_moves(job.events, cfg)
    primed = set()
    for s in steps:
        if isinstance(s, Prime):
            assert not primed, f"{s.motor} primed while {primed} still is"
            primed.add(s.motor)
        elif isinstance(s, Retract):
            primed.discard(s.motor)
    assert not primed


def test_pause_and_shared_plunger_board(cfg):
    # one plunger board for everything, syringe swapped by hand between colours
    cfg.ufp.plungers[2] = MotorBoard(port=cfg.ufp.plungers[0].port, id=cfg.ufp.plungers[0].id)
    cfg.ufp.retract_steps = 4
    cfg.print.pause_between_colors = True
    job = svg_to_job(TWO, cfg)
    steps = plan_motor_moves(job.events, cfg)
    assert motors_used(steps) == ["a", "b", "e0"]
    assert sum(isinstance(s, Pause) for s in steps) == 1
    seen = []
    with simulated_machine(cfg, plungers_used(steps), time_scale=400.0) as machine:
        run(steps, machine, on_pause=seen.append)
        assert machine.syringes["e0"].position == pytest.approx(
            job.stats["print_length"] * cfg.ufp.plunger_steps_per_mm, abs=1.0)
    assert len(seen) == 1 and "nozzle 2" in seen[0]
    # the shared plunger only ever rests further forward
    rest, pos = [], 0.0
    for s in steps:
        if isinstance(s, (Prime, Extrude)):
            pos += s.steps
        elif isinstance(s, Retract):
            pos -= s.steps
            rest.append(pos)
    assert rest == sorted(rest)
    assert rest[-1] == pytest.approx(job.stats["print_length"] * cfg.ufp.plunger_steps_per_mm)


def test_two_colour_preview_renders(cfg, tmp_path):
    job = svg_to_job(TWO, cfg)
    render(job.events, cfg, tmp_path / "two_color.png")
    assert (tmp_path / "two_color.png").stat().st_size > 0
