import json
from pathlib import Path

import ufp
from serial.tools import list_ports

MAPPING_FILE = Path(__file__).resolve().parent / "mapping.json"


def load_mapping():
    """{motor_id (int): {"function": str, "action": str}} from mapping.json; empty if unreadable."""
    try:
        with open(MAPPING_FILE) as f:
            return {int(k): v for k, v in json.load(f).items()}
    except (OSError, ValueError) as e:
        print(f"warning: could not read {MAPPING_FILE.name}: {e}")
        return {}


def id_for(function, mapping=None):
    """Motor id whose "function" in mapping.json is `function` (e.g. "ID_A"). Raises KeyError if absent."""
    mapping = load_mapping() if mapping is None else mapping
    for motor_id, info in mapping.items():
        if info.get("function") == function:
            return motor_id
    raise KeyError(f"no motor with function {function!r} in {MAPPING_FILE.name}")


def describe_motor(motor_id, mapping=None):
    """e.g. '4 (ID_SYRINGE: Syringe plunger (extrudes batter))', or '7 (unmapped)'."""
    mapping = load_mapping() if mapping is None else mapping
    info = mapping.get(motor_id)
    if not info:
        return f"{motor_id} (unmapped)"
    return f"{motor_id} ({info['function']}: {info['action']})"


def print_connected(motor_ids):
    """Print 'You are connected to motors with ID ...' plus what each one does."""
    mapping = load_mapping()
    ids = sorted(motor_ids)
    if not ids:
        print("No motors connected.")
        return
    print("You are connected to motors with ID " + ", ".join(str(i) for i in ids))
    for i in ids:
        print("  " + describe_motor(i, mapping))

# MEASURED CONSTANTS: change if not aligned with reality
MM_PER_TURN = 8.0  # vertical movement by lead screw every turn (mm)
VOLUME_PER_CM = 15.81  # cm^3 of volume per cm of height descended in plunger

class ExtrusionStepper:
    def __init__(self, port_name=None, start_current = 0.2, speed=200, accel=1000, client=None):
        self._volume_per_turn = MM_PER_TURN / 10 * VOLUME_PER_CM # cm^3
        # reuse an already-open client (e.g. from find_devices) to avoid opening the port twice
        self.m = client if client is not None else ufp.connect(port_name)
        # Initialize current position as zero, and limit current for USB
        self.m.set_current(start_current)
        self.m.set_position(0)
        self._target_steps = 0.0  # absolute commanded position (full steps)
        self.speed = speed
        self.accel = accel

    def _turn_n(self, n=1):
        """
        Turn n rotations at a provided speed. 

        One rotation is 200 steps, so speed=200 turns at 2pi rad/s 
        Accleration is fixed at 1000 steps/s / s
        """
        self._target_steps += n * 200
        print(self._target_steps)
        self.m.set_target_position(round(self._target_steps), self.speed, self.accel)

    def extrude_volume(self, volume_cc):
        turns = volume_cc / self._volume_per_turn
        self._turn_n(turns)
        return turns

    @property
    def moving(self):
        """Class property that can be probed. True if motor moving."""
        return self.m.get_states().is_moving

    def close(self):
        """Cut motor current (stops the hiss) and release the port."""
        try:
            self.m.set_current(0)
        finally:
            self.m.close()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        self.close()

# copy from scripts.find_devices here for import ease
def find_devices(pattern="usbmodem", timeout=0.5):
    """Return {motor_id: (port, client)} for every UFP board that has get_id."""
    found = {}
    for p in list_ports.comports():
        if pattern not in p.device:
            continue
        try:
            dev = ufp.connect(p.device, timeout=timeout)
        except Exception:
            continue
        try:
            if "get_id" not in dev.functions:
                dev.close()
                continue
            found[dev.get_id()] = (p.device, dev)
        except Exception:
            dev.close()  # don't leak the open port if get_id fails
            continue
    return found
