"""Enterprise DDL generation — wraps existing blce_generate_ddl patterns."""
from __future__ import annotations

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

from .contracts import (
    ConformedDimension,
    EnterpriseBusMatrix,
    EnterpriseSchema,
    FactAlignment,
    _new_id,
)

logger = logging.getLogger(__name__)


class EnterpriseDDLGenerator:
    """Generate complete enterprise schema DDL."""

    def __init__(self, schema_prefix: str = ""):
        self._schema_prefix = schema_prefix

    def generate_fact_ddl(
        self,
        alignment: FactAlignment,
        target_table: str,
    ) -> str:
        """Generate DDL for an enterprise fact table from alignment."""
        fq = f"{self._schema_prefix}{target_table}"
        cols = sorted(alignment.column_mapping.keys())

        lines = [f"CREATE OR REPLACE TABLE {fq} ("]
        for col in cols:
            lines.append(f"  {col} VARIANT,")
        lines.append("  SOURCE_SYSTEM VARCHAR(128),")
        lines.append("  LOADED_AT TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()")
        lines.append(");")

        return "\n".join(lines)

    def generate_dim_ddl(
        self,
        dim: ConformedDimension,
    ) -> str:
        """Generate DDL for a conformed dimension table."""
        from .conformed_dim_master import ConformedDimMaster
        master = ConformedDimMaster()
        return master.generate_dim_ddl(dim, self._schema_prefix)

    def generate_all_ddl(
        self,
        facts: List[FactAlignment],
        dimensions: List[ConformedDimension],
        fact_names: Optional[Dict[str, str]] = None,
    ) -> EnterpriseSchema:
        """Generate complete enterprise DDL.

        Args:
            facts: All fact alignments
            dimensions: All conformed dimensions
            fact_names: Optional mapping of alignment_id → target table name
        """
        ddl_statements: List[str] = []
        systems: set = set()

        # Schema creation
        if self._schema_prefix:
            schema_name = self._schema_prefix.rstrip(".")
            ddl_statements.append(f"CREATE SCHEMA IF NOT EXISTS {schema_name};")
            ddl_statements.append(f"USE SCHEMA {schema_name};")
            ddl_statements.append("")

        # Dimension DDL
        for dim in dimensions:
            ddl = self.generate_dim_ddl(dim)
            ddl_statements.append(f"-- Conformed Dimension: {dim.dimension_name}")
            ddl_statements.append(ddl)
            ddl_statements.append("")
            for src in dim.source_dims:
                systems.add(src.get("system", ""))

        # Fact DDL
        for alignment in facts:
            name_map = fact_names or {}
            target = name_map.get(alignment.alignment_id, f"ENT_FACT_{alignment.alignment_id[-8:].upper()}")
            ddl = self.generate_fact_ddl(alignment, target)
            ddl_statements.append(f"-- Enterprise Fact: {target}")
            ddl_statements.append(ddl)
            ddl_statements.append("")
            for src in alignment.source_facts:
                systems.add(src.get("system", ""))

        # UNION SQL for facts
        from .fact_harmonizer import FactHarmonizer
        harmonizer = FactHarmonizer()
        for alignment in facts:
            if alignment.union_sql:
                ddl_statements.append(f"-- Insert data for {alignment.alignment_id}")
                ddl_statements.append(alignment.union_sql)
                ddl_statements.append("")

        return EnterpriseSchema(
            name=self._schema_prefix.rstrip(".") or "ENTERPRISE_DW",
            facts=facts,
            dimensions=dimensions,
            ddl_statements=ddl_statements,
            source_systems=sorted(systems - {""}),
        )

    def generate_deploy_script(
        self,
        schema: EnterpriseSchema,
    ) -> str:
        """Generate a deployable SQL script from an EnterpriseSchema."""
        header = [
            "-- ============================================================",
            f"-- Enterprise DW Deployment Script: {schema.name}",
            f"-- Source Systems: {', '.join(schema.source_systems)}",
            f"-- Facts: {len(schema.facts)} | Dimensions: {len(schema.dimensions)}",
            "-- ============================================================",
            "",
        ]
        return "\n".join(header + schema.ddl_statements)
