import re

class PlacaMercosul:
    """
    Validator and Converter for Mercosur License Plates (Brazil standard).
    Format: LLL1L11 (e.g., ABC1D23)
    Legacy: LLL-1234 (e.g., ABC-1234)
    """
    
    # Mapping for conversion (Number -> Letter)
    # 0=A, 1=B, 2=C, 3=D, 4=E, 5=F, 6=G, 7=H, 8=I, 9=J
    CONVERSION_MAP = {
        '0': 'A', '1': 'B', '2': 'C', '3': 'D', '4': 'E',
        '5': 'F', '6': 'G', '7': 'H', '8': 'I', '9': 'J'
    }
    # Reverse mapping (Letter -> Number)
    REVERSE_MAP = {v: k for k, v in CONVERSION_MAP.items()}

    @classmethod
    def validate(cls, plate: str) -> bool:
        """Validates if the plate is in Mercosur or Legacy format."""
        plate = plate.upper().replace('-', '')
        
        # Check Mercosur format (LLL1L11)
        if re.match(r'^[A-Z]{3}[0-9][A-Z][0-9]{2}$', plate):
            return True
            
        # Check Legacy format (LLL1234)
        if re.match(r'^[A-Z]{3}[0-9]{4}$', plate):
            return True
            
        return False

    @classmethod
    def to_mercosur(cls, plate: str) -> str:
        """Converts a legacy plate to Mercosur format."""
        plate = plate.upper().replace('-', '')
        
        if re.match(r'^[A-Z]{3}[0-9][A-Z][0-9]{2}$', plate):
            return plate # Already Mercosur
            
        if not re.match(r'^[A-Z]{3}[0-9]{4}$', plate):
            raise ValueError("Invalid legacy plate format")
            
        # Convert 5th character (index 4) from number to letter
        # LLL N NNN -> LLL N L NN
        # 012 3 456
        char_to_convert = plate[4]
        new_char = cls.CONVERSION_MAP[char_to_convert]
        
        return f"{plate[:4]}{new_char}{plate[5:]}"

    @classmethod
    def to_legacy(cls, plate: str) -> str:
        """Converts a Mercosur plate to legacy format (if possible)."""
        plate = plate.upper().replace('-', '')
        
        if re.match(r'^[A-Z]{3}[0-9]{4}$', plate):
            return plate # Already Legacy
            
        if not re.match(r'^[A-Z]{3}[0-9][A-Z][0-9]{2}$', plate):
            raise ValueError("Invalid Mercosur plate format")
            
        # Convert 5th character (index 4) from letter to number
        char_to_convert = plate[4]
        try:
            new_char = cls.REVERSE_MAP[char_to_convert]
        except KeyError:
            raise ValueError(f"Cannot convert letter '{char_to_convert}' back to number (only A-J supported for this position)")
            
        return f"{plate[:4]}{new_char}{plate[5:]}"
