"""
Base utilities and configuration helpers for invoice movement services.
"""

import logging
import configparser
from typing import Optional

logger = logging.getLogger(__name__)


class ConfigHelper:
    """Helper for reading configuration files."""
    
    @staticmethod
    def get_met_trans_config() -> int:
        """
        Read MetTrans configuration from Scaii.ini file.
        
        Returns:
            MetTrans value (0 or 1)
        """
        try:
            config = configparser.ConfigParser()
            config.read('Scaii.ini') 
            met_trans = config.getint('METTRANS', 'TipoCambio', fallback=0)
            logger.debug(f"INI met_trans value: {met_trans}")
            return met_trans
        except Exception as e:
            logger.warning(f"Could not read Scaii.ini, using default met_trans=0: {e}")
            return 0


class StringHelper:
    """Helper for string manipulation."""
    
    @staticmethod
    def remove_commas(text: Optional[str]) -> Optional[str]:
        """Remove commas from text for CSV compatibility."""
        if not text:
            return text
        return text.replace(',', '')
    
    @staticmethod
    def clean_text(text: Optional[str]) -> Optional[str]:
        """Clean text by stripping whitespace and removing special characters."""
        if not text:
            return None
        # Remove special characters and extra whitespace
        cleaned = text.strip()
        return cleaned if cleaned else None


class DateHelper:
    """Helper for date-related operations."""
    
    @staticmethod
    def get_fecha_tipo_cambio(
        fecha_pago,
        fecha_inicio,
        tipo_pedimento: str,
        use_transport_method: bool,
        met_trans: int
    ):
        """
        Determine which date to use for exchange rate lookup based on MetTrans logic.
        
        Args:
            fecha_pago: Payment date
            fecha_inicio: Start/entry date
            tipo_pedimento: Pedimento type code
            use_transport_method: Whether to apply transport method logic
            met_trans: MetTrans configuration value
            
        Returns:
            Date to use for exchange rate lookup
        """
        fecha = fecha_pago
        
        # MetTrans# = 1 logic: use fecha_inicio for specific pedimento types
        if use_transport_method and met_trans == 1:
            if tipo_pedimento in ('1', '4', '98E'):
                fecha = fecha_inicio
        
        return fecha
