"""
UART Data decoder for Chapter 10 data types
Supports UART Data Format 0 (0x50)
"""

import struct
from typing import Dict, Any, Optional
from .base import DataTypeDecoder, DecodedPayload


class UARTDecoder(DataTypeDecoder):
    """Decoder for UART Data type (0x50)"""
    
    def __init__(self):
        super().__init__()
        self.data_type_base = 0x50
        self.data_type_name = "UART Data"
        self.supported_formats = [0x50]
    
    def can_decode(self, data_type: int) -> bool:
        return data_type == 0x50
    
    def get_data_type_name(self, data_type: int) -> str:
        return "UART Data Format 0"
    
    def decode(self, payload: bytes, ch10_header: Dict[str, Any]) -> Optional[DecodedPayload]:
        """Decode UART payload"""
        decoded_data = {}
        errors = []
        
        # Parse IPH
        iph = self._parse_intra_packet_header(payload)
        if iph:
            decoded_data.update(iph)
            data_start = iph['data_start']
        else:
            data_start = 0
            errors.append("Failed to parse intra-packet header")
        
        # Parse UART data
        if data_start < len(payload):
            uart_data = payload[data_start:]
            decoded_data['uart_data_length'] = len(uart_data)
            
            # Try to decode as text
            try:
                text_data = uart_data.decode('ascii', errors='ignore')
                decoded_data['ascii_data'] = text_data
                decoded_data['printable_chars'] = sum(1 for c in text_data if c.isprintable())
            except:
                decoded_data['ascii_decode_failed'] = True
            
            # Raw hex representation
            decoded_data['raw_hex'] = uart_data[:256].hex()  # First 256 bytes
            
            # Basic statistics
            decoded_data['null_count'] = uart_data.count(0)
            decoded_data['cr_count'] = uart_data.count(ord('\r'))
            decoded_data['lf_count'] = uart_data.count(ord('\n'))
        
        return DecodedPayload(
            data_type=0x50,
            data_type_name="UART Data Format 0",
            format_version=0,
            decoded_data=decoded_data,
            raw_payload=payload,
            errors=errors,
            metadata={'decoder': 'UARTDecoder'}
        )