"""Interactive: type "x y cc" and the stage moves to (x, y) while the syringe extrudes cc.

    > 100 50 15     move to (100, 50) mm and push 15 cc at the same time
    > 100 50 0      just move
    > 100 50 -15    move and pull back 15 cc (only as far back as you have pushed, position 0 = start)
    > q             quit
"""
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))                    # utils.py
sys.path.insert(0, str(HERE.parent / "scripts")) # wrappers

from utils import MM_PER_TURN, VOLUME_PER_CM, print_connected  # measured constants, same as extrude.py
from xy_stage_wrapper import XYStage
from syringe_wrapper import Syringe
from find_devices import find_devices

ID_A, ID_B, ID_SYRINGE = 1, 2, 4                 # MOTOR_IDs of the boards
# Swapping A and B keeps X and flips Y. The Y limit switch is on board 2, which is now index 0 (A).
SWITCH_X_MOTOR, SWITCH_Y_MOTOR = 1, 0
STAGE_SPEED = 20.0                               # mm/s

STEPS_PER_TURN = 200
CC_PER_TURN = MM_PER_TURN / 10 * VOLUME_PER_CM   # same formula as ExtrusionStepper
STEPS_PER_CC = STEPS_PER_TURN / CC_PER_TURN


def find_ports():
    """{motor_id: port} for the boards we need; closes the discovery connections so the wrappers can open them."""
    found = find_devices()
    ports = {mid: port for mid, (port, _) in found.items()}
    for _, client in found.values():
        client.close()
    missing = [i for i in (ID_A, ID_B, ID_SYRINGE) if i not in ports]
    if missing:
        sys.exit(f"boards with id {missing} not found; found ids {sorted(ports)}")
    return ports


def main():
    ports = find_ports()
    print_connected(ports)
    with XYStage(ports[ID_A], ports[ID_B], switch_x_motor=SWITCH_X_MOTOR,
                  switch_y_motor=SWITCH_Y_MOTOR, coil_current=0.99) as stage, Syringe(ports[ID_SYRINGE]) as syr:   # stage homes on connect
        print(f"{STEPS_PER_CC:.2f} steps per cc. Enter: x y cc   (q to quit)")
        last_line = None
        while True:
            line = input("> ").strip()
            if not line:
                if last_line is None:
                    continue
                line = last_line  # Enter repeats the last valid command
                print(f"(repeating: {line})")
            if line in ("q", "quit"):
                break
            try:
                x, y, cc = map(float, line.split())
            except ValueError:
                print("need three numbers: x y cc")
                continue
            last_line = line
            try:
                stage.move_to(x, y, v=STAGE_SPEED)    # returns at once
                syr._push(cc * STEPS_PER_CC)          # also returns at once, so both move together
                stage.wait()
                syr.wait()
            except Exception as e:
                stage.stop(); syr.stop()
                print("error:", e)
            else:
                print("at", tuple(round(v, 2) for v in stage.get_xy()))


if __name__ == "__main__":
    try:
        main()
    except (KeyboardInterrupt, EOFError):
        print("\nExiting")
