"""Hierarchy build workflow.

Reuses:
    - ``src.hierarchy.service.HierarchyService``
    - ``src.hierarchy.graph_bridge.HierarchyGraphBridge``
"""

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 HierarchyBuildWorkflow(BaseWorkflow):
    """Create and configure a hierarchy project.

    Manages the full lifecycle: project creation, node insertion,
    source mapping, formula configuration, and graph bridge sync.

    Reuses:
        - ``src.hierarchy.service.HierarchyService.create_project()``
        - ``src.hierarchy.service.HierarchyService.create_hierarchy()``
        - ``src.hierarchy.graph_bridge.HierarchyGraphBridge``
    """

    name = "hierarchy_reporting.hierarchy_build"
    category = "hierarchy_reporting"
    description = "Create and configure a hierarchy project with graph sync"
    required_params = ["project_name"]
    optional_params = {
        "description": "",
        "nodes": [],
        "source_mappings": [],
        "sync_to_graph": 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._create_project(params, ctx)]
        if params.get("nodes"):
            steps.append(self._add_nodes(params, ctx))
        if params.get("source_mappings"):
            steps.append(self._map_sources(params, ctx))
        if params.get("sync_to_graph"):
            steps.append(self._sync_graph(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",
            "Use WrightPipelineWorkflow.compile_to_snowflake() for DDL generation",
        )

    @workflow_step("create_project", "Create hierarchy project")
    def _create_project(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        # REUSE: src.hierarchy.service.HierarchyService(data_dir).create_project(
        #     name=params["project_name"],
        #     description=params.get("description", ""),
        # )
        raise NotImplementedStubError(
            self.name,
            "create_project",
            "src.hierarchy.service.HierarchyService.create_project(name, description)",
        )

    @workflow_step("add_nodes", "Add hierarchy nodes")
    def _add_nodes(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        # REUSE: For each node in params["nodes"]:
        #   HierarchyService.create_hierarchy(project_id, hierarchy_name, parent_id, ...)
        raise NotImplementedStubError(
            self.name,
            "add_nodes",
            "src.hierarchy.service.HierarchyService.create_hierarchy(project_id, name, parent_id)",
        )

    @workflow_step("map_sources", "Configure source mappings")
    def _map_sources(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        # REUSE: HierarchyService.add_source_mapping(hierarchy_id, mapping_config)
        raise NotImplementedStubError(
            self.name,
            "map_sources",
            "src.hierarchy.service.HierarchyService.add_source_mapping(hierarchy_id, mapping)",
        )

    @workflow_step("sync_graph", "Sync hierarchy to knowledge graph")
    def _sync_graph(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        # REUSE: src.hierarchy.graph_bridge.HierarchyGraphBridge.sync(project_id)
        raise NotImplementedStubError(
            self.name,
            "sync_graph",
            "src.hierarchy.graph_bridge.HierarchyGraphBridge.sync(project_id)",
        )
