"""Your tests for the pipeline here."""
import io
from pathlib import Path

import numpy as np
import pytest

from config import load_config
from pipeline import svg_to_job
from toolpath import ExtrudeOff, ExtrudeOn, Move, OutOfBoundsError

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


def svg(body, w=100, h=100): # create an svg string
    return io.StringIO(f'<svg xmlns="http://www.w3.org/2000/svg" width="{w}mm" height="{h}mm" '
                       f'viewBox="0 0 {w} {h}">{body}</svg>')


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


def test_square_fits_print_area_in_mm(cfg):
    cfg.design.fit_to_print_area = False                 # keep SVG physical size
    job = svg_to_job(svg('<rect x="10" y="10" width="40" height="20" stroke="black" fill="none"/>'), cfg)
    b = job.paths[0].points
    assert np.allclose(b.max(axis=0) - b.min(axis=0), [40, 20], atol=1e-6)
    a = cfg.print_area
    cx, cy = (a.x_min + a.x_max) / 2, (a.y_min + a.y_max) / 2
    assert np.allclose(b.mean(axis=0), [cx, cy], atol=1e-6)


def test_fit_preserves_aspect_and_stays_inside(cfg):
    job = svg_to_job(svg('<rect x="0" y="0" width="100" height="50" stroke="black" fill="none"/>'), cfg)
    pts = job.paths[0].points
    w, h = pts.max(axis=0) - pts.min(axis=0)
    assert w / h == pytest.approx(2.0)
    assert all(cfg.print_area.contains(x, y) for x, y in pts)


def test_svg_y_axis_is_flipped(cfg):
    # point drawn near the top of the SVG must end up at larger machine Y
    job = svg_to_job(svg('<path d="M10 10 L10 90" stroke="black"/>'), cfg)
    p = job.paths[0].points          # placed geometry keeps source point order
    assert p[0][1] > p[-1][1]


def test_travel_and_print_moves_alternate_with_extrusion(cfg):
    job = svg_to_job(ROOT / "data" / "svg" / "hi.svg", cfg)
    extruding = False
    for e in job.events:
        if isinstance(e, ExtrudeOn):
            extruding = True
        elif isinstance(e, ExtrudeOff):
            extruding = False
        elif isinstance(e, Move):
            assert e.printing == extruding
    assert job.stats["strokes"] == 8 and job.stats["travel_length"] > 0


def test_nozzle_offset_is_compensated(cfg):
    cfg.nozzles[0].offset = (10.0, -5.0)
    job = svg_to_job(svg('<line x1="10" y1="50" x2="90" y2="50" stroke="black"/>'), cfg)
    first_move = next(e for e in job.events if isinstance(e, Move))
    bed = job.paths[0].points
    assert (first_move.x, first_move.y) in {(bed[0][0] - 10, bed[0][1] + 5), (bed[-1][0] - 10, bed[-1][1] + 5)}


def test_design_is_fitted_where_the_nozzle_can_reach(cfg):
    # with this offset the gantry can't bring nozzle 0 to bed x < 100: the design shrinks to fit
    cfg.nozzles[0].offset = (100.0, 0.0)
    job = svg_to_job(svg('<circle cx="50" cy="50" r="40" stroke="black" fill="none"/>'), cfg)
    assert job.paths[0].points[:, 0].min() >= 100 - 1e-6
    assert all(cfg.travel_limits.contains(e.x, e.y) for e in job.events if isinstance(e, Move))


def test_unreachable_print_area_raises(cfg):
    cfg.nozzles[0].offset = (400.0, 0.0)   # nozzle can't reach any of the print area
    with pytest.raises(ValueError, match="reachable"):
        svg_to_job(svg('<circle cx="50" cy="50" r="40" stroke="black" fill="none"/>'), cfg)
