"""
Mapeo fila CSV → datos para ExchangeRate.
"""
from datetime import datetime
from decimal import Decimal
from typing import Dict, Any, Optional

from .common_validators import (
    parse_date,
    parse_decimal_positive,
)

CURRENCY_MAX = 7


def _str_or_none(val: Any, max_len: Optional[int] = None) -> Optional[str]:
    if val is None:
        return None
    s = str(val).strip()
    if not s:
        return None
    if max_len and len(s) > max_len:
        return s[:max_len]
    return s


def row_to_exchange_rate_data(
    row_norm: Dict[str, Any], tenant_id: int, company_id: int, date_format_preference: Optional[str] = None
) -> Dict[str, Any]:
    """Build dict for ExchangeRate model. Returns {} if FECHA or VALOR invalid."""
    parsed_date = parse_date(row_norm.get("FECHA"), date_format_preference)
    value_decimal = parse_decimal_positive(row_norm.get("VALOR"))
    if not parsed_date or value_decimal is None:
        return {}
    local = _str_or_none(row_norm.get("MONEDA_LOCAL"), CURRENCY_MAX)
    if local:
        local = local.upper()
    foreign = _str_or_none(row_norm.get("MONEDA_EXTRANJERA"), CURRENCY_MAX)
    if foreign:
        foreign = foreign.upper()
    return {
        "tenant_id": tenant_id,
        "company_id": company_id,
        "date": parsed_date,
        "value": value_decimal,
        "local_currency": local,
        "foreign_currency": foreign,
    }
