"""Financial Forensics Audit Workflow.

Reuses:
    - ``databridge.forensics.audit_standard(mapping_file, data_file, summary_file, target_period)``
    - ``databridge.forensics.audit_advanced(coa_file, inv_file, ledger_file, model_file)``
"""

from __future__ import annotations

from typing import Any, Dict, List, Optional

from databridge_core.sdk.core.context import SDKContext
from databridge_core.sdk.core.exceptions import NotImplementedStubError
from databridge_core.sdk.core.types import CompiledArtifact, Result
from databridge_core.sdk.workflows.base import BaseWorkflow
from databridge_core.sdk.workflows.result import WorkflowResult
from databridge_core.sdk.workflows.step import workflow_step


class AuditWorkflow(BaseWorkflow):
    """Performs forensic analysis on financial records.

    Supports both 'standard' (FP&A mappings) and 'advanced' (Ledger/Invoices)
    modes.  Delegates to ``databridge.forensics`` library functions.
    """

    name = "forensics.audit"
    category = "forensics"
    description = "Run financial anomaly detection (schema drift, fraud, errors)"
    required_params = ["audit_mode"]
    optional_params = {
        # Standard params
        "mapping_file": None,
        "data_file": None,
        "summary_file": None,
        "target_period": "Dec_2025",
        # Advanced params
        "coa_file": None,
        "inv_file": None,
        "ledger_file": None,
        "model_file": None,
    }

    def validate(self, params: Dict[str, Any]) -> Dict[str, Any]:
        self._check_required(params)
        params = self._apply_defaults(params)

        from databridge_core.sdk.core.exceptions import ValidationError

        mode = params.get("audit_mode")
        if mode == "standard":
            if not all([params.get("mapping_file"), params.get("data_file"), params.get("summary_file")]):
                raise ValidationError(
                    "Standard audit requires mapping_file, data_file, and summary_file."
                )
        elif mode == "advanced":
            if not all([params.get("coa_file"), params.get("inv_file"), params.get("ledger_file")]):
                raise ValidationError(
                    "Advanced audit requires coa_file, inv_file, and ledger_file."
                )
        else:
            raise ValidationError("audit_mode must be 'standard' or 'advanced'.")

        return params

    def execute(
        self, params: Dict[str, Any], ctx: Optional[SDKContext] = None
    ) -> Result:
        steps = [self._run_audit(params, ctx)]
        return WorkflowResult.from_steps(self.name, steps)

    def compile_to_snowflake(
        self, params: Dict[str, Any], ctx: Optional[SDKContext] = None
    ) -> List[CompiledArtifact]:
        raise NotImplementedStubError(
            self.name,
            "compile_to_snowflake",
            "Generate a Snowflake stored procedure that runs forensic checks "
            "against staged data using the same logic as audit_standard/advanced",
        )

    @workflow_step("run_audit", "Execute the forensic audit")
    def _run_audit(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        from databridge.forensics import audit_advanced, audit_standard

        if params["audit_mode"] == "standard":
            return audit_standard(
                mapping_file=params["mapping_file"],
                data_file=params["data_file"],
                summary_file=params["summary_file"],
                target_period=params["target_period"],
            )
        else:
            return audit_advanced(
                coa_file=params["coa_file"],
                inv_file=params["inv_file"],
                ledger_file=params["ledger_file"],
                model_file=params.get("model_file"),
            )
