"""
Audit Log Core Logic: Reference Generation and Mapping
"""
from typing import Optional, Dict, Any, Tuple

class ReferenceGenerator:
    """
    Generates legacy-style references (e.g., FUSE0-040-10)
    """

    @staticmethod
    def generate_invoice_reference(invoice_data: Dict[str, Any]) -> str:
        """
        Format: {SYSTEM}-{CUSTOMS}-{YEAR}
        Example: FUSE0-040-10
        """
        # Default values
        system = "FUSE0"
        customs = "000"
        year = "00"

        # Try to extract system (invoice_type usually holds this key)
        if invoice_data.get("invoice_type"):
            system = str(invoice_data["invoice_type"])

        # Try to extract customs (need to look into nested compliance_mx if available, or just use default)
        # Since this receives a dictionary from the mapper, we might not have deep nested relations resolved
        # We'll try to do our best with available data
        
        # Try to get year from invoice_date
        if invoice_data.get("invoice_date"):
            try:
                # invoice_date can be a date object or string
                d = invoice_data["invoice_date"]
                if hasattr(d, "year"):
                     y = d.year
                else:
                     # Assume string YYYY-MM-DD
                     y = int(str(d)[:4])
                year = str(y)[-2:]
            except:
                pass
        
        return f"{system}-{customs}-{year}"

    @staticmethod
    def generate_invoice_item_reference(invoice_ref: str, item_data: Dict[str, Any]) -> str:
        """
        Format: {INVOICE_REF}-{ITEM_PART}
        Example: FUSE0-040-10-FUS035
        """
        part_number = item_data.get("part_number", "ITEM")
        return f"{invoice_ref}-{part_number}"

    @staticmethod
    def generate_pedimento_reference(pedimento_data: Dict[str, Any]) -> str:
        """
        Format: {LICENSE}-{CUSTOMS}{YEAR}{NUMBER}
        Example: 0756C-040010315
        """
        license = str(pedimento_data.get("license", "0000")).strip()
        customs = str(pedimento_data.get("customs_office", "000")).zfill(3)
        year = str(pedimento_data.get("year", "00")).zfill(2)
        number = str(pedimento_data.get("pedimento_number", "0000000")).zfill(7)
        
        return f"{license}-{customs}{year}{number}"


class AuditMapper:
    """
    Maps table names and operations to English Procedures and Movements
    """
    
    # Map table names to Legacy Procedures (English)
    TABLE_TO_PROCEDURE = {
        # Invoices
        "invoice_header": "IMPORT INVOICE BROWSE", # BROWSEOFACIMP
        "invoice_sales_details": "IMPORT INVOICE UPDATE", # UPDATEOFACIMP
        "invoice_compliance_mx": "IMPORT INVOICE UPDATE",
        "invoice_financials": "IMPORT INVOICE UPDATE",
        "invoice_logistics": "IMPORT INVOICE UPDATE",
        "invoice_collections": "IMPORT INVOICE UPDATE",
        
        # Exports would be similar but we start with general
        
        # Pedimentos
        "pedimentos": "PEDIMENTO BROWSE", # BROWSEPEDIMEN
        
        # System
        "users": "SYSTEM SCAF",
        "sessions": "SYSTEM SCAF",
        
        # General fallbacks
        "clients_and_providers": "CATALOGS",
        "items": "CATALOGS",
        "parts": "CATALOGS",
        "customs_brokers": "CATALOGS",
        "customs_brokers_vu": "CATALOGS",
        "customs_brokers_personnel": "CATALOGS",
        "classes": "CATALOGS",
        "classification_concepts": "CATALOGS",
        "concepts": "CATALOGS",
        "customs_broker_concepts": "CATALOGS",
        "depreciation_catalog": "CATALOGS",
        "electronic_notices": "ELECTRONIC NOTICES",
        "equivalencies": "CATALOGS",
        "error_catalogs": "CATALOGS",
        "fda_catalog": "CATALOGS",
        "inpc": "CATALOGS",
        "legends": "CATALOGS",
        "multi_currency_types": "CATALOGS",
        "packages": "CATALOGS",
        "ports": "CATALOGS",
        "prevalidators": "CATALOGS",
        "seal": "CATALOGS",
        "seals": "CATALOGS",
        "signatures": "CATALOGS",
        "tariff_fractions": "CATALOGS",
        "unit_conversions": "CATALOGS",
        "us_tariff_fractions": "CATALOGS",
        
        # DODA
        "doda": "DODA",
        "doda_containers": "DODA",
        "doda_pedimentos": "DODA",
    }

    # Map (Table, Operation) to Legacy Movements (English)
    OPERATION_TO_MOVEMENT = {
        ("invoice_header", "CREATE"): "ADD IMPORT_INVOICE",
        ("invoice_header", "UPDATE"): "EDIT IMPORT_INVOICE",
        ("invoice_header", "DELETE"): "DELETE IMPORT_INVOICE",
        
        ("invoice_sales_details", "CREATE"): "ADD IMPORT_INVOICE_ITEM",
        ("invoice_sales_details", "UPDATE"): "EDIT IMPORT_INVOICE_ITEM",
        ("invoice_sales_details", "DELETE"): "DELETE IMPORT_INVOICE_ITEM",
        ("invoice_compliance_mx", "CREATE"): "ADD IMPORT_INVOICE",
        ("invoice_compliance_mx", "UPDATE"): "EDIT IMPORT_INVOICE",
        ("invoice_compliance_mx", "DELETE"): "DELETE IMPORT_INVOICE",
        ("invoice_financials", "CREATE"): "ADD IMPORT_INVOICE",
        ("invoice_financials", "UPDATE"): "EDIT IMPORT_INVOICE",
        ("invoice_financials", "DELETE"): "DELETE IMPORT_INVOICE",
        ("invoice_logistics", "CREATE"): "ADD IMPORT_INVOICE",
        ("invoice_logistics", "UPDATE"): "EDIT IMPORT_INVOICE",
        ("invoice_logistics", "DELETE"): "DELETE IMPORT_INVOICE",
        ("invoice_collections", "CREATE"): "ADD IMPORT_INVOICE",
        ("invoice_collections", "UPDATE"): "EDIT IMPORT_INVOICE",
        ("invoice_collections", "DELETE"): "DELETE IMPORT_INVOICE",
        
        ("pedimentos", "CREATE"): "ADD PEDIMENTO",
        ("pedimentos", "UPDATE"): "EDIT PEDIMENTO",
        ("pedimentos", "DELETE"): "DELETE PEDIMENTO",
        
        ("auth", "LOGIN"): "SYSTEM LOGIN",
        ("auth", "LOGOUT"): "SYSTEM LOGOUT",
        
        ("classes", "CREATE"): "ADD CLASS",
        ("classes", "UPDATE"): "EDIT CLASS",
        ("classes", "DELETE"): "DELETE CLASS",
        
        ("doda", "CREATE"): "ADD DODA",
        ("doda", "UPDATE"): "EDIT DODA",
        ("doda", "DELETE"): "DELETE DODA",
        
        ("company", "CREATE"): "ADD COMPANY",
        ("company", "UPDATE"): "EDIT COMPANY",
        ("company", "DELETE"): "DELETE COMPANY",
        ("companies", "CREATE"): "ADD COMPANY",
        ("companies", "UPDATE"): "EDIT COMPANY",
        ("companies", "DELETE"): "DELETE COMPANY",
    }

    @staticmethod
    def map_to_legacy_format(
        table_name: str,
        record_id: str,
        operation_type: str,
        username: str,
        system: str = "SCAF"
    ) -> Dict[str, Any]:
        """
        Returns dictionary with keys: reference, procedure, movement, username, system
        """
        # Determine Procedure
        procedure = AuditMapper.TABLE_TO_PROCEDURE.get(
            table_name, 
            table_name.upper().replace("_", " ") # Fallback
        )

        # Determine Movement
        movement_key = (table_name, operation_type)
        movement = AuditMapper.OPERATION_TO_MOVEMENT.get(
            movement_key,
            f"{operation_type} {table_name.upper()}"
        )

        # Determine Reference Base
        if operation_type in ["LOGIN", "LOGOUT"]:
            reference = operation_type
        else:
            reference = record_id or "NO-REF"

        return {
            "reference": reference,
            "procedure": procedure,
            "movement": movement,
            "username": username,
            "system": system
        }
