from decimal import Decimal
from sqlalchemy.orm import Session
from api.v1.modules.a76.general_catalogs.unit_conversions.models import UnitConversion
from api.v1.modules.a76.general_catalogs.equivalencies.models import EquivalencyItem

def _get_unit_equivalence(
    db: Session,
    from_unit: str,
    to_unit: str,
    tenant_id: str,
    company_id: str,
) -> tuple[str, Decimal]:
    """
    Busca una conversión entre dos unidades de medida.
    Paridad: REVEQUIVALENCIA (Clarion SCAII).

    Busca primero en el catálogo de Conversiones (unit_conversions) y,
    si no encuentra, en el catálogo de Equivalencias (equivalency_items).

    Retorna (multi_divide, factor_conv):
      - ('M', factor) → multiplicar cantidad por factor
      - ('D', factor) → dividir cantidad por factor
      - ('',  0)      → no existe equivalencia
    """
    # ── 1. Catálogo de Conversiones ──────────────────────────────────────────
    conv = (
        db.query(UnitConversion)
        .filter(
            UnitConversion.tenant_id == tenant_id,
            UnitConversion.company_id == company_id,
            UnitConversion.from_unit_code == from_unit,
            UnitConversion.to_unit_code == to_unit,
        )
        .first()
    )
    if conv and conv.conversion_factor:
        return "M", conv.conversion_factor

    conv_inv = (
        db.query(UnitConversion)
        .filter(
            UnitConversion.tenant_id == tenant_id,
            UnitConversion.company_id == company_id,
            UnitConversion.from_unit_code == to_unit,
            UnitConversion.to_unit_code == from_unit,
        )
        .first()
    )
    if conv_inv and conv_inv.conversion_factor:
        return "D", conv_inv.conversion_factor

    # ── 2. Catálogo de Equivalencias (fallback) ──────────────────────────────
    eq = (
        db.query(EquivalencyItem)
        .filter(
            EquivalencyItem.tenant_id == tenant_id,
            EquivalencyItem.company_id == company_id,
            EquivalencyItem.original_field == from_unit,
            EquivalencyItem.external_field == to_unit,
        )
        .first()
    )
    if eq:
        factor = eq.conversion_factor if eq.conversion_factor else Decimal(1)
        return "M", factor

    eq_inv = (
        db.query(EquivalencyItem)
        .filter(
            EquivalencyItem.tenant_id == tenant_id,
            EquivalencyItem.company_id == company_id,
            EquivalencyItem.original_field == to_unit,
            EquivalencyItem.external_field == from_unit,
        )
        .first()
    )
    if eq_inv:
        factor = eq_inv.conversion_factor if eq_inv.conversion_factor else Decimal(1)
        return "D", factor

    return "", Decimal(0)
