"""Semantic model workflow — Cortex Analyst integration.

Reuses:
    - ``src.cortex_agent.semantic_model.SemanticModelManager``
    - ``src.cortex_agent.metric_suggester`` (auto-discovery)
"""

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 SemanticModelWorkflow(BaseWorkflow):
    """Generate a Cortex Analyst semantic model from hierarchy or tables.

    Reuses:
        - ``src.cortex_agent.semantic_model.SemanticModelManager``
        - ``src.cortex_agent.metric_suggester.auto_generate_model()``
    """

    name = "hierarchy_reporting.semantic_model"
    category = "hierarchy_reporting"
    description = "Generate Cortex Analyst semantic model with auto-discovered metrics"
    required_params = ["project_id"]
    optional_params = {
        "auto_discover_metrics": True,
        "output_format": "yaml",
    }

    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._generate_model(params, ctx)]
        if params.get("auto_discover_metrics"):
            steps.append(self._discover_metrics(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))
            steps.append(self._graph_ingest_kb(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 Cortex Analyst YAML semantic model file and "
            "CREATE STAGE + PUT for deployment",
        )

    @workflow_step("generate_model", "Generate semantic model")
    def _generate_model(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        # REUSE: src.cortex_agent.semantic_model.SemanticModelManager
        #        .generate_from_project(project_id)
        raise NotImplementedStubError(
            self.name,
            "generate_model",
            "src.cortex_agent.semantic_model.SemanticModelManager.generate_from_project(project_id)",
        )

    @workflow_step("discover_metrics", "Auto-discover metrics and dimensions")
    def _discover_metrics(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        # REUSE: src.cortex_agent.metric_suggester.auto_generate_model(...)
        raise NotImplementedStubError(
            self.name,
            "discover_metrics",
            "src.cortex_agent.metric_suggester.auto_generate_model(table_info)",
        )

    # --- Graph integration ---

    @workflow_step("graph_record_lineage", "Record EXPORT_ARTIFACT node in lineage")
    def _graph_record_lineage(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        # ctx.graphs.record_lineage_node("sdk", f"semantic_model:{project_id}",
        #     "EXTERNAL", description="Cortex Analyst semantic model")
        raise NotImplementedStubError(
            self.name,
            "graph_record_lineage",
            "ctx.graphs.record_lineage_node — EXPORT_ARTIFACT for semantic model",
        )

    @workflow_step("graph_index_vectors", "Index semantic model in vector store")
    def _graph_index_vectors(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        # ctx.graphs.index_content(
        #     doc_id=f"semantic_{project_id}", content=model_yaml,
        #     source_type="semantic_model", metadata={...},
        # )
        raise NotImplementedStubError(
            self.name,
            "graph_index_vectors",
            "ctx.graphs.index_content(doc_id, content, 'semantic_model', metadata)",
        )

    @workflow_step("graph_ingest_kb", "Ingest metrics into KB graph")
    def _graph_ingest_kb(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        # ctx.graphs.ingest_kb_nodes(
        #     nodes=[{"id": metric_name, "type": "Column", "properties": {...}}],
        # )
        raise NotImplementedStubError(
            self.name,
            "graph_ingest_kb",
            "ctx.graphs.ingest_kb_nodes(nodes) — discovered metrics as KB nodes",
        )
