"""CLI: print an SVG on the UFP stepper boards.
Example:
    python scripts/print_ufp.py design.svg [-c config.yaml] [-o out_dir] [--dry-run] [--show]
"""
import argparse
import time
from pathlib import Path

from config import load_config
from motion import motion_stats, plan_motor_moves
from pipeline import svg_to_job
from preview import render
from ufp_driver import board_spec, motors_used, open_machine, plungers_used, run, simulated_machine

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


def main(argv=None):
    ap = argparse.ArgumentParser(description="Print an SVG with the UFP stepper boards.")
    ap.add_argument("svg")
    ap.add_argument("-c", "--config", default=DEFAULT_CONFIG)
    ap.add_argument("-o", "--out", default="out", help="where to write the preview image (default: ./out)")
    ap.add_argument("--dry-run", action="store_true", help="simulate the boards instead of connecting")
    ap.add_argument("--show", action="store_true", help="open an interactive preview window first")
    args = ap.parse_args(argv)

    cfg = load_config(args.config)
    job = svg_to_job(args.svg, cfg)
    steps = plan_motor_moves(job.events, cfg)
    names = motors_used(steps)

    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    stem = Path(args.svg).stem
    render(job.events, cfg, out / f"{stem}.png", title=stem)
    s, m = job.stats, motion_stats(steps)
    print(f"{stem}: {s['strokes']} strokes, print {s['print_length']:.0f} mm, travel {s['travel_length']:.0f} mm, "
          f"{m['moves']} motor moves, ~{m['time'] / 60:.1f} min (stopping at every point), "
          f"motors {', '.join(names)} -> preview {out / stem}.png")
    for color, n in job.color_map.items():
        mm = s["print_length_by_nozzle"].get(n, 0.0)
        print(f"  colour {color or '(none)'} -> nozzle {n} ({cfg.nozzles[n].name}), "
              f"nozzle total {mm:.0f} mm of line")
    if args.show:                         # interactive window; the script continues once it is closed
        import matplotlib.pyplot as plt
        render(job.events, cfg, title=stem)
        plt.show()

    if args.dry_run:      # the firmware's simulated boards, through the same wrappers as a real print
        with simulated_machine(cfg, plungers_used(steps)) as machine:
            run(steps, machine, on_pause=lambda msg: print(f"  (pause) {msg}")) # on_pause is a function that prints the pause message
            x, y = machine.xy
            print(f"dry run OK, gantry parked at ({x:.2f}, {y:.2f}) mm, syringes (steps): "
                  + ", ".join(f"{n}={m.position:.1f}" for n, m in machine.syringes.items()))
        return

    u = cfg.ufp
    for n in names:
        b = board_spec(u, n)
        print(f"  motor {n}: {b.port}" + (f" (MOTOR_ID {b.id})" if b.id is not None else ""))
    input("Make sure both XY carriages are free to travel towards their limit switches, and load the "
          "syringe. The gantry homes first, then the print starts. Press Enter to start, Ctrl+C to stop at any time... ")
    machine = open_machine(cfg, plungers_used(steps))   # checks every MOTOR_ID, then homes the XY stage
    try:
        run(steps, machine, on_progress=_progress, on_pause=_pause)
        print("\ndone")
    except BaseException as e:            # Ctrl+C or any error: stop the motors first
        machine.stop()
        time.sleep(0.5)                   # let them ramp down before the current is cut
        if not isinstance(e, KeyboardInterrupt):
            raise
        print("\nstopped by user")
    finally:
        machine.close()


def _pause(message):
    input(f"\n{message} Press Enter to continue (Ctrl+C to stop)... ")


def _progress(i, n):
    if i == n or i % max(1, n // 20) == 0:
        print(f"\r  step {i}/{n} ({100 * i // n}%)", end="", flush=True)


if __name__ == "__main__":
    main()

