"""
Semilla V2 para el sistema de permisos.
Corrige las descripciones erróneas y organiza los permisos por módulos reales.
Utiliza el PermissionRegistry para la modulación por API.
"""

from .registry import registry
from .seed import seed_invoices, seed_user, seed_report, seed_roles

# ============================================================================
# HELPER: LIMPIEZA DE MÓDULOS DESDE SEED.PY
# ============================================================================
def clean_seed_permissions(perms):
    """
    Toma los permisos de seed.py (que vienen todos como module='invoice')
    y los re-asigna al módulo correcto según su prefijo para la UI.
    """
    cleaned = []
    for code, desc, _, action in perms:
        module = "invoice_imp" # Default
        if code.startswith("user."): module = "users"
        elif code.startswith("report."): module = "reports"
        elif code.startswith("roles."): module = "roles"
        elif code.startswith("invoice.exp"): module = "invoice_exp"
        
        cleaned.append((code, desc, module, action))
    return cleaned

# ============================================================================
# PERMISOS DE USUARIOS (CORREGIDOS)
# ============================================================================

# ============================================================================
# AUDITORÍA Y BITÁCORA
# ============================================================================
permissions_audit = [
    ("audit_logs.view", "Ver bitácora de movimientos", "audit_logs", "view"),
]

# ============================================================================
# DATOS DE REFERENCIA (Catálogos Fijos - Solo Ver)
# ============================================================================
permissions_reference = [
    ("ref_pedimento_regimens.view", "Ver Regímenes de Pedimento", "reference_data", "view"),
    ("ref_containers.view", "Ver Contenedores", "reference_data", "view"),
    ("ref_countries.view", "Ver Países", "reference_data", "view"),
    ("ref_currency_types.view", "Ver Tipos de Moneda", "reference_data", "view"),
    ("ref_customs_sections.view", "Ver Secciones Aduaneras", "reference_data", "view"),
    ("ref_customs_warehouses.view", "Ver Recintos Fiscalizados", "reference_data", "view"),
    ("ref_incoterms.view", "Ver Incoterms", "reference_data", "view"),
    ("ref_invoice_types.view", "Ver Tipos de Factura", "reference_data", "view"),
    ("ref_material_types.view", "Ver Tipos de Material", "reference_data", "view"),
    ("ref_payment_methods.view", "Ver Formas de Pago", "reference_data", "view"),
    ("ref_pedimento_codes.view", "Ver Claves de Pedimento", "reference_data", "view"),
    ("ref_sectors.view", "Ver Sectores", "reference_data", "view"),
    ("ref_states.view", "Ver Estados", "reference_data", "view"),
    ("ref_transport_modes.view", "Ver Modos de Transporte", "reference_data", "view"),
    ("ref_transport_types.view", "Ver Tipos de Transporte", "reference_data", "view"),
    ("ref_valuation_methods.view", "Ver Métodos de Valoración", "reference_data", "view"),
]

# ============================================================================
# CATÁLOGOS GENERALES (CRUD)
# ============================================================================
def gen_crud(resource, desc, module):
    return [
        (f"{resource}.view", f"Ver {desc}", module, "view"),
        (f"{resource}.create", f"Crear {desc}", module, "create"),
        (f"{resource}.edit", f"Editar {desc}", module, "edit"),
        (f"{resource}.delete", f"Eliminar {desc}", module, "delete"),
    ]

permissions_general = (
    gen_crud("cat_company", "Información de la Empresa", "general_catalogs") +
    gen_crud("cat_packages", "Bultos", "general_catalogs") +
    gen_crud("cat_concepts", "Conceptos", "general_catalogs") +
    gen_crud("cat_broker_concepts", "Conceptos de Agente Aduanal", "general_catalogs") +
    gen_crud("cat_classification", "Clasificación de Conceptos", "general_catalogs") +
    gen_crud("cat_identifiers", "Identificadores", "general_catalogs") +
    gen_crud("cat_inpc", "INPC", "general_catalogs") +
    gen_crud("cat_legends", "Leyendas Fijas", "general_catalogs") +
    gen_crud("cat_seals", "Sellos", "general_catalogs") +
    gen_crud("cat_ports", "Puertos", "general_catalogs") +
    gen_crud("cat_um_general", "UdM Generales", "general_catalogs") +
    gen_crud("cat_um_customs", "UdM Aduana MEX", "general_catalogs") +
    gen_crud("cat_um_american", "UdM Aduana AME", "general_catalogs") +
    gen_crud("cat_um_ace", "UdM ACE", "general_catalogs") +
    gen_crud("cat_um_oma", "UdM OMA", "general_catalogs") +
    gen_crud("cat_unit_conversions", "Conversiones", "general_catalogs") +
    gen_crud("cat_equivalencies", "Equivalencias", "general_catalogs") +
    gen_crud("cat_exchange_rates", "Tipos de Cambio", "general_catalogs") +
    gen_crud("cat_multi_currency_types", "Tipos de Moneda (Múltiples)", "general_catalogs") +
    gen_crud("cat_signatures", "Firmas Electrónicas", "general_catalogs") +
    gen_crud("cat_errors", "Catálogo de Errores", "general_catalogs") +
    gen_crud("cat_doda", "DODA", "general_catalogs") +
    gen_crud("cat_prevalidators", "Prevalidadores", "general_catalogs") +
    gen_crud("cat_notices", "Avisos Electrónicos", "general_catalogs") +
    gen_crud("cat_sectors", "Sectores", "general_catalogs") +
    gen_crud("cat_locations", "Ubicaciones", "general_catalogs") +
    gen_crud("cat_depreciation_catalog", "Catálogo de Depreciación", "general_catalogs")
)

# ============================================================================
# FRACCIONES
# ============================================================================
permissions_fractions = [
    # Solo ver para SITAR
    ("frac_sitar.view", "Ver Fracciones SITAR", "fractions", "view"),
    ("frac_sitar_7.view", "Ver Fracciones SITAR (Séptima Enmienda)", "fractions", "view"),
    ("frac_sitar_us.view", "Ver Fracciones SITAR (USA)", "fractions", "view"),
] + gen_crud("frac_american", "Fracciones Americanas", "fractions") + \
    gen_crud("frac_canadian", "Fracciones Canadienses", "fractions") + \
    gen_crud("frac_historical", "Fracciones Históricas", "fractions") + \
    [("frac_sectors.view", "Ver Sectores", "fractions", "view")]

# ============================================================================
# TRANSPORTES (CRUD)
# ============================================================================
permissions_transports = (
    gen_crud("transporters", "Transportistas", "transports") +
    gen_crud("drivers", "Conductores", "transports") +
    gen_crud("trailers", "Trailers", "transports") +
    gen_crud("vehicles", "Vehículos", "transports")
)

# ============================================================================
# MERCANCÍAS (CRUD)
# ============================================================================
permissions_goods = (
    gen_crud("goods_classes", "Clases de Activo Fijo", "goods") +
    gen_crud("goods_parts", "Partes / Productos", "goods") +
    gen_crud("goods_fda", "Códigos FDA", "goods")
)

# ============================================================================
# PEDIMENTOS
# ============================================================================
permissions_pedimentos = (
    gen_crud("pedimentos_mgmt", "Gestión de Pedimentos", "pedimentos") +
    [
        ("pedimentos_codes.view", "Ver Claves de Pedimento", "pedimentos", "view"),
        ("pedimentos_regimes.view", "Ver Regímenes Aduanales", "pedimentos", "view"),
        ("pedimentos_payments.view", "Ver Formas de Pago", "pedimentos", "view"),
        ("pedimentos_sections.view", "Ver Secciones Aduaneras", "pedimentos", "view"),
        ("pedimentos_anexo22.view", "Ver Anexo 22 / Apéndice 31", "pedimentos", "view"),
    ]
)

# ============================================================================
# EXPORTACIÓN
# ============================================================================
permissions_export = (
    [("export_catalog.view", "Ver Catálogo Base Exportación", "export", "view")] +
    [("export_repair.view", "Ver Reparaciones", "export", "view")] +
    gen_crud("export_manifest", "Manifiestos de Exportación", "export") +
    [("export_proforma.view", "Ver Proformas", "export", "view")] +
    [("export_reports.view", "Ver Reportes Oficiales Exportación", "export", "view")] +
    [("export_used.view", "Ver Materiales Utilizados", "export", "view")] +
    [("export_destruction.view", "Ver Destrucciones", "export", "view")] +
    [("export_special.view", "Ver Procesos Especiales", "export", "view")]
)

# ============================================================================
# FACTURACIÓN, USUARIOS, REPORTES Y ROLES (DESDE SEED.PY)
# ============================================================================
# Estas secciones se nutren directamente de seed.py
permissions_invoice_imp_seed = clean_seed_permissions(seed_invoices)
permissions_users_seed = clean_seed_permissions(seed_user)
permissions_reports_seed = clean_seed_permissions(seed_report)
permissions_roles_seed = clean_seed_permissions(seed_roles)

# ============================================================================
# CLIENTES Y PROVEEDORES (CRUD)
# ============================================================================
permissions_clients = gen_crud("partners_mgmt", "Clientes y Proveedores", "partners")

# ============================================================================
# AGENTES ADUANALES (CRUD)
# ============================================================================
permissions_brokers = gen_crud("customs_brokers", "Agentes Aduanales", "brokers")

# ======================================# USUARIOS DEL SISTEMA (YA NO SE USA AQUÍ, VIENE DE SEED.PY)
# ============================================================================
# permissions_users = ...

# ============================================================================
# CONFIGURACIÓN GENERAL Y AYUDA
# ============================================================================
permissions_settings = [
    ("settings_general.view", "Ver Configuración General", "settings", "view"),
    ("settings_general.edit", "Editar Configuración General", "settings", "edit"),
]

permissions_help = gen_crud("help_center", "Centro de Ayuda y Documentos", "help")

# ============================================================================
# CSV UPLOAD MASIVO
# ============================================================================
permissions_csv = [
    ("csv_upload.process", "Procesar Cargas Masivas CSV", "csv_upload", "process"),
]

def register_core_permissions():
    """Registra los permisos granulados de la aplicación según Sidebar."""
    registry.register_many(permissions_audit)
    registry.register_many(permissions_reference)
    registry.register_many(permissions_general)
    registry.register_many(permissions_fractions)
    registry.register_many(permissions_transports)
    registry.register_many(permissions_goods)
    registry.register_many(permissions_pedimentos)
    
    # Registro de permisos desde seed.py (limpios)
    registry.register_many(permissions_invoice_imp_seed)
    registry.register_many(permissions_users_seed)
    registry.register_many(permissions_reports_seed)
    registry.register_many(permissions_roles_seed)

    registry.register_many(permissions_export)
    registry.register_many(permissions_clients)
    registry.register_many(permissions_brokers)
    registry.register_many(permissions_settings)
    registry.register_many(permissions_help)
    registry.register_many(permissions_csv)

# Ejecutar registro al importar este módulo
register_core_permissions()
