"""Smart Excel import workflow.

Reuses:
    - ``databridge.ingestion.smart_import_excel(file_path, sheet_name)``
    - ``databridge.ingestion.detect_anchor_cell(df_raw)``
    - ``databridge.ingestion.intelligent_unpivot(df, id_vars, entity_keywords)``

IKE integration (optional):
    - P1 Knowledge Base: Ingest imported schema into institutional memory
"""

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 SmartImportWorkflow(BaseWorkflow):
    """Intelligently import messy Excel files with anchor detection and unpivot.

    Handles Excel spreadsheets with logo rows, merged cells, and multi-level
    headers by finding the 'True Header Row' automatically. Optionally
    transforms wide tables into long (unpivoted) format.

    When IKE is available, imported schema patterns are ingested into IKE's
    P1 knowledge base so future imports benefit from institutional memory.

    Reuses:
        - ``databridge.ingestion.smart_import_excel(file_path, sheet_name)``
        - ``databridge.ingestion.detect_anchor_cell(df_raw)``
        - ``databridge.ingestion.intelligent_unpivot(df, id_vars)``
    """

    name = "data_cleaning.smart_import"
    category = "data_cleaning"
    description = "Smart Excel import with anchor detection, trimming, and unpivot"
    required_params = ["file_path"]
    optional_params = {
        "sheet_name": 0,
        "unpivot": False,
        "id_columns": None,
        "entity_keywords": None,
        "ike_ingest": 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._detect_anchor(params, ctx),
            self._import_excel(params, ctx),
        ]
        if params.get("unpivot") and params.get("id_columns"):
            steps.append(self._unpivot(params, ctx))
        # IKE P1: Ingest schema into institutional KB
        if params.get("ike_ingest") and ctx and ctx.ike.available:
            steps.append(self._ike_ingest_schema(params, ctx))
        # Graph integration
        if ctx and ctx.graphs.available:
            steps.append(self._graph_record_lineage(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 COPY INTO with header detection pre-processing",
        )

    @workflow_step("detect_anchor", "Detect true header row in messy Excel")
    def _detect_anchor(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        # REUSE: databridge.ingestion.detect_anchor_cell(df_raw)
        raise NotImplementedStubError(
            self.name,
            "detect_anchor",
            "databridge.ingestion.detect_anchor_cell(df_raw)",
        )

    @workflow_step("import_excel", "Import Excel with anchor-based trimming")
    def _import_excel(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        # REUSE: databridge.ingestion.smart_import_excel(file_path, sheet_name)
        raise NotImplementedStubError(
            self.name,
            "import_excel",
            "databridge.ingestion.smart_import_excel(file_path, sheet_name)",
        )

    @workflow_step("unpivot", "Transform wide table to long format")
    def _unpivot(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        # REUSE: databridge.ingestion.intelligent_unpivot(df, id_vars, entity_keywords)
        raise NotImplementedStubError(
            self.name,
            "unpivot",
            "databridge.ingestion.intelligent_unpivot(df, id_vars, entity_keywords)",
        )

    @workflow_step("ike_ingest_schema", "Ingest imported schema into IKE KB")
    def _ike_ingest_schema(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        raise NotImplementedStubError(
            self.name,
            "ike_ingest_schema",
            "ctx.ike.ingest_knowledge(content, source_type='excel_import') — IKE P1 KB ingest",
        )

    # --- Graph integration ---

    @workflow_step("graph_record_lineage", "Record EXCEL_SOURCE and COLUMN nodes in lineage")
    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 — EXCEL_SOURCE + COLUMN nodes from import",
        )

    @workflow_step("graph_index_vectors", "Index imported schema 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, 'excel_import', metadata)",
        )
