"""Invoice Graph search workflow — semantic search, vendor profiles, validation.

Wraps ``src.invoice_graph.unified.dispatch_invoice_graph_search`` as an SDK
workflow so AI agents can trigger invoice search 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 InvoiceGraphSearchWorkflow(BaseWorkflow):
    """Search the Invoice Knowledge Graph — invoices, vendors, products.

    Actions: search_invoices, search_vendors, search_products,
             find_similar, vendor_profile, product_stats, validate_invoice.
    """

    name = "invoice_graph.search"
    category = "invoice_graph"
    description = (
        "Search the Invoice Knowledge Graph for invoices, vendors, "
        "products, and validate new invoices against learned patterns"
    )
    required_params = ["action"]
    optional_params = {
        "query": "",
        "invoice_id": "",
        "vendor_id": "",
        "product_id": "",
        "invoice_data": "",
        "top_k": 10,
    }

    def validate(self, params: Dict[str, Any]) -> Dict[str, Any]:
        self._check_required(params)
        action = params["action"]
        valid = [
            "search_invoices", "search_vendors", "search_products",
            "find_similar", "vendor_profile", "product_stats", "validate_invoice",
        ]
        if action not in valid:
            from databridge_core.sdk.core.exceptions import ValidationError

            raise ValidationError(
                f"{self.name}: invalid action '{action}'. Choose from {valid}"
            )
        return self._apply_defaults(params)

    def execute(
        self, params: Dict[str, Any], ctx: Optional[SDKContext] = None
    ) -> Result:
        steps = [self._run_search(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 search runs locally — no Snowflake DDL compilation.",
        )

    @workflow_step("invoice_graph_search", "Run invoice graph search action")
    def _run_search(
        self, params: Dict[str, Any], ctx: Optional[SDKContext] = None
    ):
        from src.invoice_graph.unified import dispatch_invoice_graph_search

        action = params["action"]
        kwargs = {"top_k": params.get("top_k", 10)}
        for key in ("query", "invoice_id", "vendor_id", "product_id", "invoice_data"):
            val = params.get(key)
            if val:
                kwargs[key] = val

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