import time
from config import load_config
from ufp_driver import simulated_machine

SCALE = 10.0   # the simulator runs 10x faster than real time
DUR = 10.0     # planned extrude time in "machine seconds"; ~1 s of wall time at SCALE 10

cfg = load_config("config/machine.example.yaml")
with simulated_machine(cfg, ["e0"], time_scale=SCALE) as m:
    bank = m.syringes

    # A: wait=False must return at once and leave the plunger moving
    bank.prime("e0")
    t = time.monotonic()
    bank.extrude("e0", 120, DUR, wait=False)
    print(f"A  returned after {time.monotonic() - t:.3f} s   (expect ~0.0)")
    print(f"A  plunger moving: {bank['e0'].is_moving()}    (expect True)")
    n = 0
    while bank["e0"].is_moving():       # poll() should finish cleanly, with no exception
        bank.poll()
        n += 1
        time.sleep(0.01)
    print(f"A  poll() ran {n} times and the move finished cleanly")
    bank.retract("e0")

    # B: default wait=True must still block for about DUR / SCALE
    bank.prime("e0")
    t = time.monotonic()
    bank.extrude("e0", 120, DUR)
    print(f"B  blocked for {time.monotonic() - t:.2f} s   (expect ~{DUR / SCALE:.1f})")
    bank.retract("e0")

    # C: the early-exit caveat. is_moving() must be True right after move_to(wait=False)
    m.stage.move_by(20, 20, v=20, a=1000, wait=False)
    print(f"C  stage moving right after move_to(wait=False): {m.stage.is_moving()}   (expect True)")
    m.stage.wait(timeout=30)
    print("C  stage finished")