from utils import ExtrusionStepper, find_devices, print_connected

MOTOR_IDS = (1, 2, 3, 4, 5)
MOTORS : dict[int, ExtrusionStepper] = {}

INSTRUCTIONS = """Enter: <motor id>, <rotations>   e.g. "4, 2", "4 2" or "2, -0.5"
Positive turns one way, negative the other. Type q to quit (or Ctrl-C)."""


def parse_command(cmd):
    """Return (motor_id, rotations) or raise ValueError with a message to show the user."""
    parts = cmd.replace(",", " ").split()  # comma and/or spaces both work
    if len(parts) != 2:
        raise ValueError('expected "<motor id>, <rotations>", e.g. "4, 2" or "4 2"')
    try:
        motor_id = int(parts[0])
    except ValueError:
        raise ValueError(f"motor id must be a whole number, got {parts[0]!r}")
    try:
        rots = float(parts[1])
    except ValueError:
        raise ValueError(f"rotations must be a number, got {parts[1]!r}")
    if motor_id not in MOTORS:
        raise ValueError(f"no motor with id {motor_id} is connected (connected: {sorted(MOTORS)})")
    return motor_id, rots


def main():
    for mid, (port, client) in find_devices().items():
        if mid in MOTOR_IDS:
            # reuse the connection find_devices already opened
            MOTORS[mid] = ExtrusionStepper(port, 0.5, client=client, speed=200, accel=400)
        else:
            client.close()

    print_connected(MOTORS)
    if not MOTORS:
        return
    print()
    print(INSTRUCTIONS)

    last_cmd = None
    try:
        while True:
            cmd = input("> ").strip()
            if not cmd:
                if last_cmd is None:
                    continue
                cmd = last_cmd  # Enter repeats the last valid command
                print(f"(repeating: {cmd})")
            if cmd.lower() in ("q", "quit", "exit"):
                break
            try:
                request_id, rots = parse_command(cmd)
            except ValueError as e:
                print(f"error: {e}")
                continue
            last_cmd = cmd
            try:
                print(f"Turning motor {request_id} by {rots:g} turns...")
                MOTORS[request_id]._turn_n(rots)
                print("Done")
            except Exception as e:
                print(f"error: motor {request_id} failed: {e}")
    except (KeyboardInterrupt, EOFError):
        pass
    finally:
        print("\nExiting")
        for motor in MOTORS.values():
            motor.close()

if __name__ == "__main__":
    main()
