from machine import Pin, PWM


class PWMMotor:
    def __init__(self, pin_ia, pin_ib, freq=1000, flip_dir=False):
        """
        :param pin_ia: Pin connected to IA on L9110S
        :param pin_ib: Pin connected to IB on L9110S
        :param freq: PWM frequency (default 1000Hz)
        :param flip_dir: Boolean to reverse logical forward/backward
        """
        # Initialize PWM on both pins
        self._pwm_a = PWM(Pin(pin_ia), freq=freq)
        self._pwm_b = PWM(Pin(pin_ib), freq=freq)

        # Start with motor off
        self._pwm_a.duty_u16(0)
        self._pwm_b.duty_u16(0)

        self._flip_dir = flip_dir
        self._speed = 0.0  # Range -1.0 to 1.0

    def set_speed(self, speed):
        """
        Sets motor speed and direction.
        :param speed: Float between -1.0 (reverse) and 1.0 (forward)
        """
        self._speed = max(-1.0, min(1.0, speed))

        # Adjust for flip_dir preference
        effective_speed = -self._speed if self._flip_dir else self._speed

        # Convert 0.0-1.0 to 16-bit duty cycle (0-65535)
        duty = int(abs(effective_speed) * 65535)

        if effective_speed > 0:
            # Forward: PWM on A, B held at 0
            self._pwm_a.duty_u16(duty)
            self._pwm_b.duty_u16(0)
        elif effective_speed < 0:
            # Reverse: B held at 0, PWM on B
            self._pwm_a.duty_u16(0)
            self._pwm_b.duty_u16(duty)
        else:
            # Stop
            self.stop()

    def stop(self):
        self._pwm_a.duty_u16(0)
        self._pwm_b.duty_u16(0)
        self._speed = 0.0

    def deinit(self):
        """Release the PWM hardware"""
        self._pwm_a.deinit()
        self._pwm_b.deinit()
