"""Invoice Graph ingestion workflow — ingest, rebuild, stats, quality check.

Wraps ``src.invoice_graph.unified.dispatch_invoice_graph_index`` as an SDK
workflow so AI agents can trigger invoice graph operations via MCP tools.
"""

from __future__ import annotations

from typing import Any, Dict, List, Optional

from databridge_core.sdk.core.context import SDKContext
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 InvoiceGraphIngestionWorkflow(BaseWorkflow):
    """Ingest invoices into the dedicated Invoice Knowledge Graph.

    Actions: ingest_batch, ingest_single, stats, quality_check, rebuild.
    """

    name = "invoice_graph.ingestion"
    category = "invoice_graph"
    description = (
        "Ingest invoice data into the Invoice Knowledge Graph, "
        "run quality checks, and manage the graph store"
    )
    required_params = ["action"]
    optional_params = {
        "mapping_dir": "",
        "file_path": "",
        "batch_size": 500,
        "start_from": 0,
        "max_files": 0,
    }

    def validate(self, params: Dict[str, Any]) -> Dict[str, Any]:
        self._check_required(params)
        action = params["action"]
        valid = ["ingest_batch", "ingest_single", "stats", "quality_check", "rebuild"]
        if action not in valid:
            from databridge_core.sdk.core.exceptions import ValidationError

            raise ValidationError(
                f"{self.name}: invalid action '{action}'. Choose from {valid}"
            )
        if action == "ingest_single" and not params.get("file_path"):
            from databridge_core.sdk.core.exceptions import ValidationError

            raise ValidationError(
                f"{self.name}: 'file_path' is required for ingest_single"
            )
        return self._apply_defaults(params)

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

    def compile_to_snowflake(
        self, params: Dict[str, Any], ctx: Optional[SDKContext] = None
    ) -> List[CompiledArtifact]:
        from databridge_core.sdk.core.exceptions import NotImplementedStubError

        raise NotImplementedStubError(
            self.name,
            "compile_to_snowflake",
            "Invoice graph ingestion runs locally — no Snowflake DDL compilation.",
        )

    @workflow_step("invoice_graph_index", "Run invoice graph indexing action")
    def _run_index(
        self, params: Dict[str, Any], ctx: Optional[SDKContext] = None
    ):
        from src.invoice_graph.unified import dispatch_invoice_graph_index

        action = params["action"]
        kwargs = {}
        for key in ("mapping_dir", "file_path", "batch_size", "start_from", "max_files"):
            val = params.get(key)
            if val:
                kwargs[key] = val

        return dispatch_invoice_graph_index(action, settings=None, **kwargs)
