"""
UFM01 CircuitPython Driver for Adafruit Metro ESP32-S2
Based on working Arduino implementation with manual hex parsing

Hardware Connections for Metro ESP32-S2:
- UFM01 TX -> Metro IO6 (UART RX)
- UFM01 RX -> Metro IO5 (UART TX)
- UFM01 VCC -> 5V
- UFM01 GND -> GND

Alternative: You can use any two IO pins that support UART

Protocol: 2400 baud, 8 data bits, Even parity, 1 stop bit
Frame Format: <3C><32>[...28 data bytes...]<16>
"""

import time
import board
import busio

# UFM01 Protocol Constants
UFM01_BAUDRATE = 2400
UFM01_START_BYTE_1 = 0x3C
UFM01_START_BYTE_2 = 0x32
UFM01_END_BYTE = 0x16
UFM01_EXPECTED_LENGTH = 32  # bytes in complete frame

# Data packet indices (from your Arduino code)
UFM_AF_START = 9    # Accumulated Flow start
UFM_AF_END = 15     # Accumulated Flow end
UFM_IF_START = 16   # Instantaneous Flow start
UFM_IF_END = 20     # Instantaneous Flow end
UFM_IF_SIGN = 20    # Sign byte for IF
UFM_TC_START = 25   # Temperature start
UFM_TC_END = 28     # Temperature end

# Command opcodes
UFM_OPCODE_CLEAR_VOLUME = 0x5A


class UFM01:
    """Driver for ScioSense UFM01 ultrasonic flow sensor"""
    
    def __init__(self, tx_pin=board.IO5, rx_pin=board.IO6, baudrate=UFM01_BAUDRATE):
        """
        Initialize UFM01 sensor
        
        Args:
            tx_pin: Board TX pin (connects to UFM01 RX) - Default IO5
            rx_pin: Board RX pin (connects to UFM01 TX) - Default IO6
            baudrate: UART baudrate (default 2400)
            
        For Metro ESP32-S2:
            Use IO5 (TX) and IO6 (RX) for hardware UART
            Or any other IO pins that support UART
        """
        # Initialize UART with Even parity (8E1)
        self.uart = busio.UART(
            tx_pin, 
            rx_pin, 
            baudrate=baudrate,
            bits=8,
            parity=busio.UART.Parity.EVEN,
            stop=1,
            timeout=0.1  # Non-blocking with short timeout
        )
        
        # Sensor readings
        self.accumulated_flow = -999.0  # Liters (invalid when < -900)
        self.instantaneous_flow = -999.0  # L/h (invalid when < -900)
        self.temperature = 0.0  # Celsius
        self.max_flow_rate = 0.0  # L/h peak
        
        # Frame parsing state
        self._frame_buffer = bytearray()
        self._hex_string = ""
        self._start1_detected = False
        self._start2_detected = False
        self._start1_previous = False
        self._frame_complete = True
        
        # Statistics
        self.stats = {
            'frames_received': 0,
            'frames_parsed': 0,
            'parse_errors': 0,
            'last_frame_time': 0
        }
        
        print("UFM01 initialized on UART")
        print(f"  Baud: {baudrate}, Parity: Even, Bits: 8, Stop: 1")
    
    @property
    def is_valid(self):
        """Check if current readings are valid"""
        return self.accumulated_flow > -900
    
    def _parse_bcd_value(self, data, start, end, divisor=1.0):
        """
        Parse BCD (Binary Coded Decimal) value from data bytes
        
        Args:
            data: bytearray of raw data
            start: Start index
            end: End index (exclusive)
            divisor: Value to divide result by
            
        Returns:
            float: Parsed value
        """
        multiplier = 1
        value = 0
        
        for x in range(start, end):
            bcd_byte = data[x]
            bcd_value = (bcd_byte & 0x0F) + ((bcd_byte >> 4) * 10)
            value += bcd_value * multiplier
            multiplier *= 100
        
        return value / divisor
    
    def _parse_accumulated_flow(self, data):
        """Parse accumulated flow from frame (BCD format, 7 bytes)"""
        value = self._parse_bcd_value(data, UFM_AF_START, UFM_AF_END, 1000.0)
        self.accumulated_flow = value
        return value
    
    def _parse_instantaneous_flow(self, data):
        """Parse instantaneous flow from frame (BCD format with sign, 5 bytes)"""
        value = self._parse_bcd_value(data, UFM_IF_START, UFM_IF_END, 100.0)
        
        # Check sign byte
        if data[UFM_IF_SIGN] == 0x80:
            value *= -1
        
        self.instantaneous_flow = value
        
        # Track maximum flow rate
        if value > self.max_flow_rate:
            self.max_flow_rate = value
        
        return value
    
    def _parse_temperature(self, data):
        """Parse temperature from frame (BCD format, 4 bytes)"""
        value = self._parse_bcd_value(data, UFM_TC_START, UFM_TC_END, 100.0)
        self.temperature = value
        return value
    
    def _process_complete_frame(self):
        """Process a complete frame and extract all values"""
        try:
            # Convert buffer to hex string for display
            self._hex_string = ''.join(f'{b:02x}' for b in self._frame_buffer)
            
            # Parse all values
            af = self._parse_accumulated_flow(self._frame_buffer)
            ifr = self._parse_instantaneous_flow(self._frame_buffer)
            temp = self._parse_temperature(self._frame_buffer)
            
            # Update statistics
            self.stats['frames_received'] += 1
            self.stats['frames_parsed'] += 1
            self.stats['last_frame_time'] = time.monotonic()
            
            # Print parsed values (comment out for production)
            print(f"\n✓ Frame received (#{self.stats['frames_received']})")
            print(f"  Accumulated Flow: {af:.3f} L")
            print(f"  Instantaneous Flow: {ifr:.1f} L/h")
            print(f"  Temperature: {temp:.1f}°C")
            print(f"  Max Flow Rate: {self.max_flow_rate:.1f} L/h")
            
            return True
            
        except Exception as e:
            print(f"✗ Frame parse error: {e}")
            self.stats['parse_errors'] += 1
            return False
    
    def _reset_frame_parser(self):
        """Reset frame parsing state machine"""
        self._start1_detected = False
        self._start2_detected = False
        self._start1_previous = False
        self._frame_complete = True
        self._frame_buffer = bytearray()  # Recreate instead of clear()
    
    def update(self):
        """
        Process incoming UART data and parse frames
        Call this frequently (in main loop) to process sensor data
        
        Returns:
            bool: True if a new frame was successfully parsed
        """
        frame_parsed = False
        
        # Process all available bytes
        while True:
            byte_data = self.uart.read(1)
            if not byte_data:
                break  # No more data available
            
            current_byte = byte_data[0]
            
            if self._start1_detected and self._start2_detected:
                # Collecting data bytes
                self._frame_buffer.append(current_byte)
                
                # Check for end of frame
                if (current_byte == UFM01_END_BYTE and 
                    len(self._frame_buffer) >= UFM01_EXPECTED_LENGTH):
                    
                    frame_parsed = self._process_complete_frame()
                    self._reset_frame_parser()
                
                self._start1_previous = False
                
            elif current_byte == UFM01_START_BYTE_1 and self._frame_complete:
                # Start of new frame
                self._frame_buffer = bytearray()  # Recreate instead of clear()
                self._frame_buffer.append(current_byte)
                self._start1_detected = True
                self._start1_previous = True
                
            elif current_byte == UFM01_START_BYTE_2 and self._start1_previous:
                # Second start byte confirmed
                self._frame_buffer.append(current_byte)
                self._start2_detected = True
                self._start1_previous = False
                self._frame_complete = False
                
            else:
                # Invalid byte sequence
                self._reset_frame_parser()
        
        return frame_parsed
    
    def clear_accumulated_flow(self):
        """
        Send command to clear sensor's accumulated flow counter
        
        Returns:
            bool: True if command sent successfully
        """
        try:
            # Build command packet (from your Arduino code)
            cmd_packet = bytearray([
                0xFE,  # Header byte 1
                0xFE,  # Header byte 2
                0x11,  # Command type
                UFM_OPCODE_CLEAR_VOLUME,  # Opcode
                0xFD,  # Value
                (UFM_OPCODE_CLEAR_VOLUME + 0xFD) & 0xFF,  # Checksum
                0x16   # End byte
            ])
            
            self.uart.write(cmd_packet)
            print("Command sent: Clear accumulated flow")
            
            # Reset local max flow rate
            self.max_flow_rate = 0.0
            
            time.sleep(0.1)  # Give sensor time to process
            return True
            
        except Exception as e:
            print(f"Error sending command: {e}")
            return False
    
    def get_last_frame_hex(self):
        """Get hex string of last received frame for debugging"""
        return self._hex_string
    
    def print_stats(self):
        """Print communication statistics"""
        print("\n=== UFM01 Statistics ===")
        print(f"Frames received: {self.stats['frames_received']}")
        print(f"Frames parsed: {self.stats['frames_parsed']}")
        print(f"Parse errors: {self.stats['parse_errors']}")
        
        if self.stats['last_frame_time'] > 0:
            elapsed = time.monotonic() - self.stats['last_frame_time']
            print(f"Time since last frame: {elapsed:.1f}s")
        
        print("========================\n")


# ============================================================================
# EXAMPLE USAGE / TEST CODE
# ============================================================================

if __name__ == "__main__":
    print("\n" + "="*50)
    print("UFM01 CircuitPython Test")
    print("Based on working Arduino implementation")
    print("="*50 + "\n")
    
    # Initialize sensor with Metro ESP32-S2 pins
    # TX=IO5, RX=IO6
    sensor = UFM01(board.IO5, board.IO6)
    
    print("\nWaiting for sensor data...")
    print("Sensor should send data automatically at ~1Hz\n")
    
    # Main loop
    loop_count = 0
    last_stats_print = time.monotonic()
    no_data_count = 0
    
    while True:
        loop_count += 1
        
        # Update sensor (process incoming data)
        if sensor.update():
            # New frame was parsed
            no_data_count = 0
            
            # Print summary line
            if sensor.is_valid:
                print(f"\n📊 Current: {sensor.instantaneous_flow:.1f} L/h | "
                      f"Total: {sensor.accumulated_flow:.2f} L | "
                      f"Temp: {sensor.temperature:.1f}°C | "
                      f"Peak: {sensor.max_flow_rate:.1f} L/h")
            else:
                print("\n⚠️  Sensor offline (no valid data)")
        else:
            # No new frame this cycle
            no_data_count += 1
            
            # Warn if no data for extended period
            if no_data_count > 50:  # ~5 seconds at 100ms per loop
                print("⏳ Waiting for data...")
                no_data_count = 0
        
        # Print statistics every 60 seconds
        if time.monotonic() - last_stats_print > 60:
            sensor.print_stats()
            last_stats_print = time.monotonic()
        
        # Small delay (sensor sends at ~1Hz, check more frequently)
        time.sleep(0.1)