"""Multilingual alias registry for Natural Language Query (NLQ).

Pure data dictionaries + simple lookup functions.
Supports PT-BR, EN, and ES.
"""

from __future__ import annotations

# ── Model Aliases ─────────────────────────────────────────────
# alias → (odoo_model, default_fields)
# Multi-word aliases MUST come before single-word to enable longest-match.

MODEL_ALIASES: dict[str, tuple[str, list[str]]] = {
    # PT-BR
    "nota fiscal": ("account.invoice", ["number", "partner_id", "date_invoice", "amount_total", "state"]),
    "notas fiscais": ("account.invoice", ["number", "partner_id", "date_invoice", "amount_total", "state"]),
    "pedido de venda": ("sale.order", ["name", "partner_id", "date_order", "amount_total", "state"]),
    "pedidos de venda": ("sale.order", ["name", "partner_id", "date_order", "amount_total", "state"]),
    "pedido de compra": ("purchase.order", ["name", "partner_id", "date_order", "amount_total", "state"]),
    "pedidos de compra": ("purchase.order", ["name", "partner_id", "date_order", "amount_total", "state"]),
    "ordem de producao": ("mrp.production", ["name", "product_id", "date_planned_start", "state"]),
    "ordens de producao": ("mrp.production", ["name", "product_id", "date_planned_start", "state"]),
    "fatura": ("account.invoice", ["number", "partner_id", "date_invoice", "amount_total", "state"]),
    "faturas": ("account.invoice", ["number", "partner_id", "date_invoice", "amount_total", "state"]),
    "empresa": ("res.company", ["name", "email", "phone"]),
    "empresas": ("res.company", ["name", "email", "phone"]),
    "parceiro": ("res.partner", ["name", "email", "phone", "is_company"]),
    "parceiros": ("res.partner", ["name", "email", "phone", "is_company"]),
    "cliente": ("res.partner", ["name", "email", "phone", "customer"]),
    "clientes": ("res.partner", ["name", "email", "phone", "customer"]),
    "fornecedor": ("res.partner", ["name", "email", "phone", "supplier"]),
    "fornecedores": ("res.partner", ["name", "email", "phone", "supplier"]),
    "produto": ("product.product", ["name", "default_code", "list_price", "qty_available"]),
    "produtos": ("product.product", ["name", "default_code", "list_price", "qty_available"]),
    "contato": ("res.partner", ["name", "email", "phone"]),
    "contatos": ("res.partner", ["name", "email", "phone"]),
    "aniversariante": ("res.partner", ["name", "email", "phone", "birthday"]),
    "aniversariantes": ("res.partner", ["name", "email", "phone", "birthday"]),
    "usuario": ("res.users", ["name", "login", "email"]),
    "usuarios": ("res.users", ["name", "login", "email"]),
    "pagamento": ("account.payment", ["name", "partner_id", "amount", "payment_date", "state"]),
    "pagamentos": ("account.payment", ["name", "partner_id", "amount", "payment_date", "state"]),
    "pedido pos": ("pos.order", ["name", "date_order", "amount_total", "config_id", "state"]),
    "pedidos pos": ("pos.order", ["name", "date_order", "amount_total", "config_id", "state"]),
    "pedido do pos": ("pos.order", ["name", "date_order", "amount_total", "config_id", "state"]),
    "pedidos do pos": ("pos.order", ["name", "date_order", "amount_total", "config_id", "state"]),
    "pedido ponto de venda": ("pos.order", ["name", "date_order", "amount_total", "config_id", "state"]),
    "pedidos ponto de venda": ("pos.order", ["name", "date_order", "amount_total", "config_id", "state"]),
    "pedido do ponto de venda": ("pos.order", ["name", "date_order", "amount_total", "config_id", "state"]),
    "pedidos do ponto de venda": ("pos.order", ["name", "date_order", "amount_total", "config_id", "state"]),
    "venda pos": ("pos.order", ["name", "date_order", "amount_total", "config_id", "state"]),
    "vendas pos": ("pos.order", ["name", "date_order", "amount_total", "config_id", "state"]),
    "vendas do pos": ("pos.order", ["name", "date_order", "amount_total", "config_id", "state"]),
    "venda do pos": ("pos.order", ["name", "date_order", "amount_total", "config_id", "state"]),
    "venda do ponto de venda": ("pos.order", ["name", "date_order", "amount_total", "config_id", "state"]),
    "vendas do ponto de venda": ("pos.order", ["name", "date_order", "amount_total", "config_id", "state"]),
    # EN
    "sale order": ("sale.order", ["name", "partner_id", "date_order", "amount_total", "state"]),
    "sale orders": ("sale.order", ["name", "partner_id", "date_order", "amount_total", "state"]),
    "purchase order": ("purchase.order", ["name", "partner_id", "date_order", "amount_total", "state"]),
    "purchase orders": ("purchase.order", ["name", "partner_id", "date_order", "amount_total", "state"]),
    "invoice": ("account.invoice", ["number", "partner_id", "date_invoice", "amount_total", "state"]),
    "invoices": ("account.invoice", ["number", "partner_id", "date_invoice", "amount_total", "state"]),
    "partner": ("res.partner", ["name", "email", "phone", "is_company"]),
    "partners": ("res.partner", ["name", "email", "phone", "is_company"]),
    "company": ("res.company", ["name", "email", "phone"]),
    "companies": ("res.company", ["name", "email", "phone"]),
    "customer": ("res.partner", ["name", "email", "phone", "customer"]),
    "customers": ("res.partner", ["name", "email", "phone", "customer"]),
    "supplier": ("res.partner", ["name", "email", "phone", "supplier"]),
    "suppliers": ("res.partner", ["name", "email", "phone", "supplier"]),
    "product": ("product.product", ["name", "default_code", "list_price", "qty_available"]),
    "products": ("product.product", ["name", "default_code", "list_price", "qty_available"]),
    "contact": ("res.partner", ["name", "email", "phone"]),
    "contacts": ("res.partner", ["name", "email", "phone"]),
    "user": ("res.users", ["name", "login", "email"]),
    "users": ("res.users", ["name", "login", "email"]),
    "payment": ("account.payment", ["name", "partner_id", "amount", "payment_date", "state"]),
    "payments": ("account.payment", ["name", "partner_id", "amount", "payment_date", "state"]),
    # ES
    "factura": ("account.invoice", ["number", "partner_id", "date_invoice", "amount_total", "state"]),
    "facturas": ("account.invoice", ["number", "partner_id", "date_invoice", "amount_total", "state"]),
    "pedido de venta": ("sale.order", ["name", "partner_id", "date_order", "amount_total", "state"]),
    "orden de compra": ("purchase.order", ["name", "partner_id", "date_order", "amount_total", "state"]),
    "socio": ("res.partner", ["name", "email", "phone", "is_company"]),
    "socios": ("res.partner", ["name", "email", "phone", "is_company"]),
}

# Sorted by length descending for longest-match-first
_SORTED_ALIASES = sorted(MODEL_ALIASES.keys(), key=len, reverse=True)


# ── Implicit Domain (alias implies extra filters) ────────────

MODEL_IMPLICIT_DOMAIN: dict[str, list[tuple]] = {
    "cliente": [("customer", "=", True)],
    "clientes": [("customer", "=", True)],
    "customer": [("customer", "=", True)],
    "customers": [("customer", "=", True)],
    "fornecedor": [("supplier", "=", True)],
    "fornecedores": [("supplier", "=", True)],
    "supplier": [("supplier", "=", True)],
    "suppliers": [("supplier", "=", True)],
}


# ── Status Map ────────────────────────────────────────────────

STATUS_MAP: dict[str, tuple[str, str, str]] = {
    # PT-BR
    "em aberto": ("state", "=", "open"),
    "aberta": ("state", "=", "open"),
    "abertas": ("state", "=", "open"),
    "aberto": ("state", "=", "open"),
    "paga": ("state", "=", "paid"),
    "pagas": ("state", "=", "paid"),
    "pago": ("state", "=", "paid"),
    "pagos": ("state", "=", "paid"),
    "rascunho": ("state", "=", "draft"),
    "cancelada": ("state", "=", "cancel"),
    "canceladas": ("state", "=", "cancel"),
    "cancelado": ("state", "=", "cancel"),
    "confirmada": ("state", "=", "sale"),
    "confirmadas": ("state", "=", "sale"),
    "confirmado": ("state", "=", "sale"),
    "feita": ("state", "=", "done"),
    "feitas": ("state", "=", "done"),
    "feito": ("state", "=", "done"),
    # EN
    "open": ("state", "=", "open"),
    "paid": ("state", "=", "paid"),
    "draft": ("state", "=", "draft"),
    "cancelled": ("state", "=", "cancel"),
    "canceled": ("state", "=", "cancel"),
    "confirmed": ("state", "=", "sale"),
    "done": ("state", "=", "done"),
    # ES
    "abierta": ("state", "=", "open"),
    "abiertas": ("state", "=", "open"),
    "pagada": ("state", "=", "paid"),
    "pagadas": ("state", "=", "paid"),
    "borrador": ("state", "=", "draft"),
}

_SORTED_STATUSES = sorted(STATUS_MAP.keys(), key=len, reverse=True)


# ── Type Map (invoice direction) ──────────────────────────────

TYPE_MAP: dict[str, tuple[str, str, str]] = {
    # PT-BR
    "de entrada": ("type", "=", "in_invoice"),
    "de saida": ("type", "=", "out_invoice"),
    "de saída": ("type", "=", "out_invoice"),
    # EN
    "incoming": ("type", "=", "in_invoice"),
    "outgoing": ("type", "=", "out_invoice"),
    "inbound": ("type", "=", "in_invoice"),
    "outbound": ("type", "=", "out_invoice"),
    # ES
    "de proveedor": ("type", "=", "in_invoice"),
    "de cliente": ("type", "=", "out_invoice"),
}

_SORTED_TYPES = sorted(TYPE_MAP.keys(), key=len, reverse=True)


# ── Boolean Filters ───────────────────────────────────────────

BOOLEAN_FILTERS: dict[str, list[tuple]] = {
    "ativos": [("active", "=", True)],
    "ativas": [("active", "=", True)],
    "ativo": [("active", "=", True)],
    "ativa": [("active", "=", True)],
    "active": [("active", "=", True)],
    "inativos": [("active", "=", False)],
    "inativas": [("active", "=", False)],
    "inativo": [("active", "=", False)],
    "inativa": [("active", "=", False)],
    "inactive": [("active", "=", False)],
    "arquivados": [("active", "=", False)],
    "arquivadas": [("active", "=", False)],
    "archived": [("active", "=", False)],
}

_SORTED_BOOLEANS = sorted(BOOLEAN_FILTERS.keys(), key=len, reverse=True)


# ── Month Names (3 languages) ────────────────────────────────

MONTH_NAMES: dict[str, int] = {
    # PT-BR
    "janeiro": 1, "fevereiro": 2, "marco": 3, "março": 3,
    "abril": 4, "maio": 5, "junho": 6,
    "julho": 7, "agosto": 8, "setembro": 9,
    "outubro": 10, "novembro": 11, "dezembro": 12,
    # EN
    "january": 1, "february": 2, "march": 3,
    "april": 4, "may": 5, "june": 6,
    "july": 7, "august": 8, "september": 9,
    "october": 10, "november": 11, "december": 12,
    # ES
    "enero": 1, "febrero": 2, "marzo": 3,
    "abril": 4, "mayo": 5, "junio": 6,
    "julio": 7, "agosto": 8, "septiembre": 9,
    "octubre": 10, "noviembre": 11, "diciembre": 12,
}


# ── Date/Amount field mappings ────────────────────────────────

DATE_FIELDS: dict[str, str] = {
    "account.invoice": "date_invoice",
    "sale.order": "date_order",
    "purchase.order": "date_order",
    "account.payment": "payment_date",
    "mrp.production": "date_planned_start",
    "pos.order": "date_order",
}

AMOUNT_FIELDS: dict[str, str] = {
    "account.invoice": "amount_total",
    "sale.order": "amount_total",
    "purchase.order": "amount_total",
    "account.payment": "amount",
    "pos.order": "amount_total",
}

# ── Group-by field mappings ───────────────────────────────────

GROUP_FIELDS: dict[str, str] = {
    "pos.order": "config_id",
}


# ── Lookup Functions ──────────────────────────────────────────

def resolve_model(text: str) -> tuple[str, list[str], str, list[tuple]] | None:
    """Find the best model match in text (longest-match-first).

    Returns (model, fields, matched_alias, implicit_domain) or None.
    """
    text_lower = text.lower()
    for alias in _SORTED_ALIASES:
        if alias in text_lower:
            model, fields = MODEL_ALIASES[alias]
            implicit = MODEL_IMPLICIT_DOMAIN.get(alias, [])
            return model, fields, alias, implicit
    return None


def get_status_clause(text: str) -> tuple[str, str, str] | None:
    """Extract status filter from text."""
    text_lower = text.lower()
    for status in _SORTED_STATUSES:
        if status in text_lower:
            return STATUS_MAP[status]
    return None


def get_type_clause(text: str) -> tuple[str, str, str] | None:
    """Extract type filter (invoice direction) from text."""
    text_lower = text.lower()
    for type_key in _SORTED_TYPES:
        if type_key in text_lower:
            return TYPE_MAP[type_key]
    return None


def get_boolean_clauses(text: str) -> list[tuple]:
    """Extract boolean filters from text."""
    text_lower = text.lower()
    clauses = []
    for key in _SORTED_BOOLEANS:
        if key in text_lower:
            clauses.extend(BOOLEAN_FILTERS[key])
            break  # Only one boolean filter at a time
    return clauses
