"""Dynamic Table compiler.

Reuses:
    - ``src.wright.pipeline_generator.MartPipelineGenerator``
    - ``src.wright.config_generator.MartConfigGenerator``
    - ``src.hierarchy.service.HierarchyService``
"""

from __future__ import annotations

import logging
from typing import Any, Dict, List, Optional

from databridge_core.sdk.compiler.base import BaseCompiler
from databridge_core.sdk.core.exceptions import CompilationError
from databridge_core.sdk.core.types import CompiledArtifact

logger = logging.getLogger(__name__)


class DynamicTableCompiler(BaseCompiler):
    """Compile SDK workflows into Snowflake Dynamic Tables.

    Leverages the Wright pipeline generator to produce the 4-object
    DDL pipeline (VW_1, DT_2, DT_3A, DT_3).

    Reuses:
        - ``src.wright.pipeline_generator.MartPipelineGenerator``
        - ``src.wright.config_generator.MartConfigGenerator``
    """

    object_type = "DYNAMIC TABLE"

    def compile(
        self,
        workflow_name: str,
        params: Dict[str, Any],
        target_database: Optional[str] = None,
        target_schema: Optional[str] = None,
    ) -> List[CompiledArtifact]:
        """Compile into Dynamic Table DDL via Wright pipeline generator.

        Required params:
            project_id: Hierarchy project ID.

        Optional params:
            output_dir: Directory for pipeline output.
            report_type: Report type label (default 'CUSTOM').
            account_segment: Account segment filter.
            data_dir: Data directory (default 'data').
        """
        # Lazy imports to avoid hard dependencies
        try:
            from src.wright.pipeline_generator import MartPipelineGenerator
            from src.wright.config_generator import MartConfigGenerator
            from src.hierarchy.service import HierarchyService
        except ImportError as exc:
            raise CompilationError(
                f"DynamicTableCompiler requires Wright and Hierarchy modules: {exc}"
            ) from exc

        project_id = params.get("project_id")
        if not project_id:
            raise CompilationError(
                "DynamicTableCompiler requires 'project_id' param"
            )

        output_dir = params.get("output_dir")
        report_type = params.get("report_type", "CUSTOM")
        account_segment = params.get("account_segment")
        data_dir = params.get("data_dir", "data")

        # Build MartConfig from hierarchy project
        hierarchy_service = HierarchyService(data_dir=data_dir)
        config_gen = MartConfigGenerator()

        try:
            config = config_gen.from_hierarchy_project(
                project_id=project_id,
                hierarchy_service=hierarchy_service,
                report_type=report_type,
                account_segment=account_segment,
                database=target_database,
                schema=target_schema,
            )
        except (ValueError, Exception) as exc:
            raise CompilationError(
                f"DynamicTableCompiler failed to build MartConfig "
                f"for project '{project_id}': {exc}"
            ) from exc

        # Generate the 4-object pipeline
        generator = MartPipelineGenerator(output_dir=output_dir)

        try:
            pipeline_objects = generator.generate_full_pipeline(config)
        except Exception as exc:
            raise CompilationError(
                f"DynamicTableCompiler pipeline generation failed: {exc}"
            ) from exc

        # Map PipelineObjects to CompiledArtifacts
        artifacts: List[CompiledArtifact] = []
        for obj in pipeline_objects:
            # Map ObjectType to artifact_type
            if obj.object_type.value == "DYNAMIC_TABLE":
                artifact_type = "dynamic_table"
            else:
                artifact_type = "view"

            # FQN-qualify dependencies
            qualified_deps = [
                self._fqn(dep, target_database, target_schema)
                if "." not in dep else dep
                for dep in obj.dependencies
            ]

            artifact = CompiledArtifact(
                artifact_type=artifact_type,
                object_name=obj.object_name,
                ddl=self._header(obj.object_name) + obj.ddl,
                dependencies=qualified_deps,
                source_workflow=workflow_name,
                metadata={
                    "layer": obj.layer.value,
                    "layer_order": obj.layer_order,
                    "description": obj.description,
                    "project_id": project_id,
                    "report_type": report_type,
                },
            )
            artifacts.append(artifact)

        logger.info(
            "DynamicTableCompiler produced %d artifacts for project '%s'",
            len(artifacts),
            project_id,
        )
        return artifacts
