"""Standalone fraud detection workflow.

Reuses:
    - ``databridge.fraud_detect.detect_fraud_patterns(file_path)``
    - ``databridge.fraud_detect.detect_fraud_batch(directory)``

IKE integration (optional):
    - P4 Scoring: Calibrate fraud confidence via Thompson + SPRT + Platt
    - P5 Learning: Feed fraud outcomes into feedback loop
"""

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 FraudDetectionWorkflow(BaseWorkflow):
    """Detect fraud patterns in financial data files.

    Runs dedicated fraud pattern detection on CSV/Excel data,
    including Benford's Law analysis, duplicate invoice detection,
    round-number bias, and temporal anomaly scoring.

    When IKE is available, detection results are scored through
    IKE's P4 engine for calibrated confidence and fed into the
    P5 learning loop for continuous improvement.

    Reuses:
        - ``databridge.fraud_detect.detect_fraud_patterns(file_path)``
        - ``databridge.fraud_detect.detect_fraud_batch(directory)``
    """

    name = "detection.fraud_detection"
    category = "detection"
    description = "Standalone fraud pattern detection with Benford, duplicates, and temporal analysis"
    required_params = ["file_path"]
    optional_params = {
        "batch_mode": False,
        "rules": None,
        "ike_scoring": True,
        "ike_feedback": True,
    }

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

    def execute(
        self, params: Dict[str, Any], ctx: Optional[SDKContext] = None
    ) -> Result:
        steps = [self._fraud_detect(params, ctx)]
        # IKE P4: Calibrate scores
        if params.get("ike_scoring") and ctx and ctx.ike.available:
            steps.append(self._ike_score_results(params, ctx))
        # IKE P5: Feed into learning loop
        if params.get("ike_feedback") and ctx and ctx.ike.available:
            steps.append(self._ike_feedback(params, ctx))
        # Graph integration
        if ctx and ctx.graphs.available:
            steps.append(self._graph_record_lineage(params, ctx))
            steps.append(self._graph_record_evidence(params, ctx))
            steps.append(self._graph_index_vectors(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 Snowflake Task calling SPCS fraud detection endpoint",
        )

    @workflow_step("fraud_detect", "Run fraud pattern detection")
    def _fraud_detect(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        # REUSE: databridge.fraud_detect.detect_fraud_patterns(file_path)
        #   or   databridge.fraud_detect.detect_fraud_batch(directory) if batch_mode
        raise NotImplementedStubError(
            self.name,
            "fraud_detect",
            "databridge.fraud_detect.detect_fraud_patterns(file_path)",
        )

    @workflow_step("ike_score_results", "Calibrate fraud scores via IKE P4")
    def _ike_score_results(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        raise NotImplementedStubError(
            self.name,
            "ike_score_results",
            "ctx.ike.batch_score(findings) — IKE P4 Thompson + SPRT + Platt",
        )

    @workflow_step("ike_feedback", "Feed fraud outcomes into IKE P5 learning loop")
    def _ike_feedback(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        raise NotImplementedStubError(
            self.name,
            "ike_feedback",
            "ctx.ike.record_feedback(finding_id, outcome) — IKE P5 learning loop",
        )

    # --- Graph integration ---

    @workflow_step("graph_record_lineage", "Record Finding nodes in lineage graph")
    def _graph_record_lineage(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        raise NotImplementedStubError(
            self.name,
            "graph_record_lineage",
            "ctx.graphs.record_lineage_node — fraud Finding→RULE edges",
        )

    @workflow_step("graph_record_evidence", "Record fraud evidence trail")
    def _graph_record_evidence(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        raise NotImplementedStubError(
            self.name,
            "graph_record_evidence",
            "ctx.graphs.record_evidence(account_id, rule_id, 'fraud_detection', confidence)",
        )

    @workflow_step("graph_index_vectors", "Index fraud findings in vector store")
    def _graph_index_vectors(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        raise NotImplementedStubError(
            self.name,
            "graph_index_vectors",
            "ctx.graphs.index_content(doc_id, content, 'fraud_finding', metadata)",
        )
