"""Matriz de permisos: una sola fuente de verdad para autorizar acciones.

Esta matriz se ESPEJA en `frontend/src/utils/permissions.js`. Si cambia algo
aquí, debe cambiarse allá. Cualquier endpoint o botón nuevo agrega una clave
aquí en lugar de hardcodear roles.

Modelo de roles (acordado 2026-05-18):
- admin: todo
- inventario: catálogo, unidades, almacenes, compras, proveedores, transferencias, reportes.
              NO toca configuración (sedes/monedas/métodos de pago/usuarios/banners) ni POS.
- vendedor (modelo mostrador): atiende caja en SU sede. Lee catálogo/stock/clientes;
            crea ventas, devoluciones, cobros, clientes. NO edita productos ni
            inventario ni compras ni configuración.
- cliente: tienda pública únicamente (no usa estas acciones).

Las asignaciones por sede (UserStoreAssignment.can_sell / can_manage_inventory)
se aplicarán como filtro EXTRA en Fase 3 — por ahora sólo gating por rol global.
"""
from functools import wraps

from flask import jsonify
from flask_jwt_extended import current_user, jwt_required

ADMIN = "admin"
INVENTARIO = "inventario"
VENDEDOR = "vendedor"
TECNICO = "tecnico"

# Operacional: los 3 roles que manejan el día a día del negocio.
# Usar para acciones que el técnico NO debe ver (sales, customers, stock, etc.)
ALL_OPS = frozenset({ADMIN, INVENTARIO, VENDEDOR})

# Staff completo INCLUYENDO técnico. Usar solo en acciones que el técnico SÍ
# necesita (lookup de items, dashboard recortado, ver productos/marcas).
ALL_STAFF = ALL_OPS | frozenset({TECNICO})

ADMIN_ONLY = frozenset({ADMIN})
ADMIN_INV = frozenset({ADMIN, INVENTARIO})
ADMIN_VEN = frozenset({ADMIN, VENDEDOR})
ADMIN_TEC = frozenset({ADMIN, TECNICO})
ADMIN_INV_TEC = frozenset({ADMIN, INVENTARIO, TECNICO})

PERMISSIONS: dict[str, frozenset[str]] = {
    # ── Dashboard ────────────────────────────────────────────────
    # Técnico también entra al dashboard (vista recortada con sus pendientes).
    "dashboard.view":           ALL_STAFF,

    # ── Productos / Catálogo ─────────────────────────────────────
    # Técnico debe poder ver productos para entender qué está reparando.
    "products.view":            ALL_STAFF,
    "products.create":          ADMIN_INV,
    "products.edit":            ADMIN_INV,
    "products.delete":          ADMIN_ONLY,
    "products.view_movements":  ALL_OPS,
    # Ajuste global de precios por markup sobre el costo (accion sensible).
    "pricing.adjust":           ADMIN_ONLY,

    # ── Marcas / Categorías ──────────────────────────────────────
    # Técnico necesita ver marca/categoría del equipo que repara.
    "brands.view":              ALL_STAFF,
    "brands.manage":            ADMIN_INV,
    "brands.delete":            ADMIN_ONLY,
    "categories.view":          ALL_STAFF,
    "categories.manage":        ADMIN_INV,
    "categories.delete":        ADMIN_ONLY,

    # ── Unidades (items serializados) ────────────────────────────
    # Técnico debe poder ver/escanear/buscar los equipos que tiene asignados.
    "items.view":               ALL_STAFF,
    "items.lookup":             ALL_STAFF,
    "items.timeline":           ALL_STAFF,
    "items.barcode_png":        ALL_STAFF,
    "items.create":             ADMIN_INV,
    "items.edit":               ADMIN_INV,
    "items.move":               ADMIN_INV,
    "items.change_status":      ADMIN_INV,
    "items.delete":             ADMIN_ONLY,

    # ── Stock global / consultas ─────────────────────────────────
    # Técnico NO debe ver el stock completo de la empresa.
    "stock.view":               ALL_OPS,

    # ── Ajuste de existencias (altas/bajas manuales con nota) ────
    "inventory.adjust":         ADMIN_INV,

    # ── Almacenes ────────────────────────────────────────────────
    "warehouses.view":          ALL_OPS,
    "warehouses.manage":        ADMIN_INV,
    "warehouses.delete":        ADMIN_ONLY,
    "warehouses.locations.manage": ADMIN_INV,
    "warehouses.inventory_pdf": ALL_OPS,

    # ── Sedes (stores) ───────────────────────────────────────────
    "stores.view":              ALL_OPS,
    "stores.manage":            ADMIN_ONLY,
    "stores.delete":            ADMIN_ONLY,
    "stores.list_users":        ADMIN_INV,
    "stores.assign_users":      ADMIN_ONLY,
    "me.stores":                ALL_OPS,

    # ── Transferencias entre sedes ───────────────────────────────
    "transfers.view":             ALL_OPS,
    "transfers.create":           ADMIN_INV,
    "transfers.send":             ADMIN_INV,
    "transfers.confirm_receipt":  ALL_OPS,   # vendedor puede pre-confirmar
    "transfers.receive":          ADMIN_INV, # solo admin/inv cierra y mueve stock
    "transfers.cancel":           ADMIN_ONLY,

    # ── Auditoría de movimientos ─────────────────────────────────
    "audit.view":               ADMIN_INV,

    # ── Leads (interacciones del bot WhatsApp con clientes potenciales) ──
    # Vendedores los ven y toman; admin puede borrar.
    "leads.view":               ALL_OPS,
    "leads.claim":              ALL_OPS,
    "leads.update":             ALL_OPS,
    "leads.delete":             ADMIN_ONLY,

    # ── iPhones usados (kind especial) ───────────────────────────
    "iphones.view":             ALL_OPS,
    "iphones.presets":          ALL_OPS,
    "iphones.models":           ALL_OPS,
    "iphones.create":           ADMIN_INV,
    "iphones.edit":             ADMIN_INV,
    "iphones.delete":           ADMIN_ONLY,

    # ── Ventas / POS ─────────────────────────────────────────────
    "sales.view":               ALL_OPS,
    "sales.create_pos":         ADMIN_VEN,
    "sales.confirm_web":        ADMIN_VEN,
    "sales.fulfill":            ALL_OPS,
    "sales.delivery_proof":     ALL_OPS,
    "sales.payment_proof":      ALL_OPS,   # vendedor/admin pueden subir comprobantes
    "sales.cancel":             ADMIN_ONLY,
    "sales.delete_attachment":  ADMIN_ONLY,

    # ── Comisiones del vendedor ──────────────────────────────────
    "commissions.view_own":     ALL_OPS,   # vendedor ve las suyas (admin/inv también)
    "commissions.view_all":     ADMIN_INV, # admin/inv ven todas
    "commissions.pay":          ADMIN_ONLY,# solo admin paga / revierte

    # ── Finanzas (dashboard ejecutivo + gastos operativos) ───────
    "finance.view":             ADMIN_ONLY,  # solo admin ve P&L consolidado
    "expenses.view":            ADMIN_ONLY,
    "expenses.create":          ADMIN_ONLY,
    "expenses.delete":          ADMIN_ONLY,

    # ── Costos (visibilidad del costo de inventario / reparación) ─
    # Dato sensible: SOLO admin. Vendedor / inventario / técnico NO ven
    # costos en las vistas compartidas (unidades, stock, ficha de producto,
    # ventas, almacén y sus PDFs). Único gate de costo del sistema: usar
    # `can_see_cost(user)` en lugar de hardcodear el rol.
    "costs.view":               ADMIN_ONLY,

    # ── Presupuestos (cotizaciones) ──────────────────────────────
    "quotes.view":              ALL_OPS,   # admin/inv/vendedor ven y arman
    "quotes.create":            ALL_OPS,
    "quotes.delete":            ADMIN_ONLY,
    "sales.invoice_pdf":        ALL_OPS,

    # ── Cuentas por cobrar / cobros ──────────────────────────────
    "receivables.view":         ALL_OPS,
    "receivables.collect":      ADMIN_VEN,
    "receivables.reverse":      ADMIN_ONLY,

    # ── Devoluciones / cambios ───────────────────────────────────
    "returns.view":             ALL_OPS,
    "returns.create":           ADMIN_VEN,
    "returns.approve":          ADMIN_ONLY,
    "returns.reject":           ADMIN_ONLY,

    # ── Garantías ────────────────────────────────────────────────
    "warranties.view":          ALL_OPS,
    "warranties.resolve":       ADMIN_ONLY,

    # ── Pérdidas / mermas ────────────────────────────────────────
    "losses.view":              ADMIN_INV,
    "losses.declare":           ADMIN_ONLY,

    # ── Clientes ─────────────────────────────────────────────────
    "customers.view":           ALL_OPS,
    "customers.create":         ADMIN_VEN,
    "customers.edit":           ADMIN_VEN,
    "customers.delete":         ADMIN_ONLY,
    "customers.statement":      ALL_OPS,

    # ── Proveedores / Compras / Por pagar ────────────────────────
    "suppliers.view":           ADMIN_INV,
    "suppliers.manage":         ADMIN_INV,
    "suppliers.delete":         ADMIN_ONLY,
    "suppliers.statement":      ADMIN_INV,
    "purchases.view":           ADMIN_INV,
    "purchases.create":         ADMIN_INV,
    "purchases.delete":         ADMIN_ONLY,
    "purchases.receive":        ADMIN_INV,
    "purchases.pdf":            ADMIN_INV,
    "payables.view":            ADMIN_INV,
    "payables.pay":             ADMIN_ONLY,
    "payables.reverse":         ADMIN_ONLY,

    # ── Configuración ────────────────────────────────────────────
    "payment_methods.view":     ALL_OPS,
    "payment_methods.manage":   ADMIN_ONLY,
    "currencies.view":          ALL_OPS,
    "currencies.manage":        ADMIN_ONLY,
    "currencies.rates.view":    ALL_OPS,
    "currencies.rates.create":  ADMIN_ONLY,

    # ── Usuarios (staff) ─────────────────────────────────────────
    "users.view":               ADMIN_ONLY,
    "users.manage":             ADMIN_ONLY,

    # ── Reportes / exportaciones ─────────────────────────────────
    "reports.view":             ADMIN_INV,
    "exports.run":              ADMIN_INV,

    # ── Banners de tienda online ─────────────────────────────────
    "banners.view":             ALL_OPS,
    "banners.manage":           ADMIN_ONLY,

    # ── Subida de imágenes ───────────────────────────────────────
    "uploads.create":           ADMIN_INV,

    # ── Servicio técnico ─────────────────────────────────────────
    # Admin/inv crea servicios, técnico ve y completa los suyos.
    # El filtro "solo los suyos" se aplica a nivel endpoint (no en la matriz).
    "technical_services.view":         ADMIN_INV_TEC,
    "technical_services.view_all":     ADMIN_INV,    # técnico solo ve los suyos via /me
    "technical_services.create":       ADMIN_INV,
    "technical_services.complete":     ADMIN_TEC,
    "technical_services.cancel":       ADMIN_ONLY,
    "technical_services.uncomplete":   ADMIN_ONLY,
    "technical_services.set_fee":      ADMIN_ONLY,
    "technical_services.describe":     ADMIN_TEC,    # escribir descripción / notas
    "technical_services.reassign":     ADMIN_ONLY,
    "technical_services.pay":          ADMIN_ONLY,
    "technical_services.reverse_pay":  ADMIN_ONLY,

    # ── Configuración del sistema (key-value) ────────────────────
    "system_config.manage":     ADMIN_ONLY,
}


def is_allowed(role: str | None, action: str) -> bool:
    """¿Puede `role` ejecutar `action`?"""
    if role is None:
        return False
    allowed = PERMISSIONS.get(action)
    if allowed is None:
        raise KeyError(f"acción desconocida: {action!r}")
    return role in allowed


def allowed_actions(role: str | None) -> list[str]:
    """Lista de acciones que puede hacer `role`. Útil para enviar al frontend."""
    if role is None:
        return []
    return [act for act, roles in PERMISSIONS.items() if role in roles]


# ──────────────────────────────────────────────────────────────────────
# Asignaciones por sede (Fase 3)
# ──────────────────────────────────────────────────────────────────────
#
# El rol determina QUÉ acciones puede hacer el usuario; las asignaciones
# (`UserStoreAssignment`) determinan EN QUÉ SEDE puede hacerlas. Admin tiene
# acceso a todas las sedes (bypass). Vendedor/Inventario sólo a las que
# tengan asignación con el flag correspondiente:
#   - can_sell           → vender en POS, cobrar, devolver
#   - can_manage_inventory → mover/transferir/ajustar unidades
#
# Si el usuario NO tiene ninguna asignación (modelo viejo) tratamos:
#   - admin: acceso global (siempre)
#   - resto: acceso vacío → debe asignarse explícitamente a una sede.


def _role_of(user) -> str | None:
    if user is None:
        return None
    return user.role.value if hasattr(user.role, "value") else user.role


def is_admin(user) -> bool:
    return _role_of(user) == ADMIN


def can_see_cost(user) -> bool:
    """¿Puede `user` ver costos? Gate ÚNICO de costo (hoy: solo admin).

    Centraliza la decisión para no repetir el rol en cada endpoint/serializer.
    Espejo en frontend: `can(user, 'costs.view')`.
    """
    return is_allowed(_role_of(user), "costs.view")


def scrub_cost(payload, user):
    """Quita la clave 'cost' de un dict (o lista de dicts) si `user` NO puede ver costos.

    Devuelve el mismo `payload` (mutado) para encadenar en el return:
        return scrub_cost(schema.dump(item), current_user)
    """
    if can_see_cost(user):
        return payload
    rows = payload if isinstance(payload, list) else [payload]
    for row in rows:
        if isinstance(row, dict):
            row.pop("cost", None)
    return payload


def sellable_store_ids(user) -> list[int] | None:
    """Devuelve la lista de store_ids donde el usuario puede vender.

    Retorna `None` si es admin (acceso global, sin filtro).
    Retorna `[]` si no tiene ninguna asignación con can_sell.
    """
    if is_admin(user):
        return None
    if user is None:
        return []
    return [a.store_id for a in (user.store_assignments or []) if a.can_sell]


def managable_store_ids(user) -> list[int] | None:
    """Igual que sellable_store_ids pero para can_manage_inventory."""
    if is_admin(user):
        return None
    if user is None:
        return []
    return [
        a.store_id
        for a in (user.store_assignments or [])
        if a.can_manage_inventory
    ]


def can_sell_in(user, store_id: int | None) -> bool:
    """¿Puede el usuario vender en la sede `store_id`?"""
    if is_admin(user):
        return True
    if store_id is None:
        return False
    return store_id in (sellable_store_ids(user) or [])


def can_manage_inventory_in(user, store_id: int | None) -> bool:
    """¿Puede el usuario mover/ajustar inventario en la sede `store_id`?"""
    if is_admin(user):
        return True
    if store_id is None:
        return False
    return store_id in (managable_store_ids(user) or [])


def require_permission(action: str):
    """Decorador: exige JWT válido + el rol del usuario en `PERMISSIONS[action]`.

    Reemplaza `@require_role("admin","vendedor",...)` por
    `@require_permission("sales.create_pos")`. Beneficio: cambiar quién puede
    qué = editar 1 línea en `PERMISSIONS`, no buscar en 27 archivos.

    Uso:
        @admin_bp.post("/sales/pos")
        @require_permission("sales.create_pos")
        def create_pos_sale(): ...
    """
    if action not in PERMISSIONS:
        raise KeyError(f"acción desconocida en require_permission: {action!r}")

    def decorator(fn):
        @wraps(fn)
        @jwt_required()
        def wrapper(*args, **kwargs):
            if current_user is None:
                return jsonify(error="no autenticado"), 401
            if not current_user.is_active:
                return jsonify(error="usuario desactivado"), 403
            role = (
                current_user.role.value
                if hasattr(current_user.role, "value")
                else current_user.role
            )
            if not is_allowed(role, action):
                return jsonify(error="permisos insuficientes", action=action), 403
            return fn(*args, **kwargs)
        return wrapper
    return decorator
