"""Enterprise DW Consolidation Engine — Pydantic contracts."""
from __future__ import annotations

import uuid
from enum import Enum
from typing import Any, Dict, List, Optional

from pydantic import BaseModel, Field


def _new_id(prefix: str = "edw") -> str:
    return f"{prefix}_{uuid.uuid4().hex[:12]}"


# ---------------------------------------------------------------------------
# Grain definitions
# ---------------------------------------------------------------------------

class GrainLevel(str, Enum):
    DAILY = "daily"
    MONTHLY = "monthly"
    QUARTERLY = "quarterly"
    YEARLY = "yearly"
    TRANSACTIONAL = "transactional"


class GrainRelationship(str, Enum):
    SAME = "same"
    A_FINER = "a_finer"
    B_FINER = "b_finer"
    INCOMPATIBLE = "incompatible"


class AlignmentStrategy(str, Enum):
    DIRECT_UNION = "direct_union"
    AGGREGATE_TO_COARSER = "aggregate_to_coarser"
    BRIDGE_TABLE = "bridge_table"


class GrainSpec(BaseModel):
    """Grain definition for a fact table."""
    table_name: str
    source_system: str
    grain_columns: List[str] = Field(default_factory=list)
    grain_level: GrainLevel = GrainLevel.TRANSACTIONAL
    row_count_estimate: int = 0
    temporal_column: str = ""


class GrainComparison(BaseModel):
    """Result of comparing grain between two fact tables."""
    system_a: str
    table_a: str
    grain_a: GrainSpec
    system_b: str
    table_b: str
    grain_b: GrainSpec
    relationship: GrainRelationship = GrainRelationship.INCOMPATIBLE
    shared_dimensions: List[str] = Field(default_factory=list)
    alignment_strategy: AlignmentStrategy = AlignmentStrategy.BRIDGE_TABLE


# ---------------------------------------------------------------------------
# Fact alignment
# ---------------------------------------------------------------------------

class FactAlignment(BaseModel):
    """Plan for aligning two or more fact tables for UNION."""
    alignment_id: str = Field(default_factory=lambda: _new_id("fal"))
    source_facts: List[Dict[str, str]] = Field(default_factory=list)
    target_grain: GrainLevel = GrainLevel.MONTHLY
    column_mapping: Dict[str, List[str]] = Field(default_factory=dict)
    unmapped_columns: Dict[str, List[str]] = Field(default_factory=dict)
    aggregate_expressions: Dict[str, str] = Field(default_factory=dict)
    union_sql: str = ""


# ---------------------------------------------------------------------------
# Conformed dimensions
# ---------------------------------------------------------------------------

class MasteringStrategy(str, Enum):
    FIRST_MATCH = "first_match"
    MOST_COMPLETE = "most_complete"
    PRIORITY_SYSTEM = "priority_system"


class ConformedDimension(BaseModel):
    """Enterprise conformed dimension definition."""
    dimension_name: str
    source_dims: List[Dict[str, str]] = Field(default_factory=list)
    enterprise_key_column: str = ""
    natural_key_mapping: Dict[str, str] = Field(default_factory=dict)
    attributes: List[str] = Field(default_factory=list)
    attribute_source_map: Dict[str, Dict[str, str]] = Field(default_factory=dict)
    scd_type: int = 1
    mastering_strategy: MasteringStrategy = MasteringStrategy.FIRST_MATCH
    priority_system: str = ""
    member_count_estimate: Dict[str, int] = Field(default_factory=dict)


class EnterpriseKeyMap(BaseModel):
    """Mapping of natural keys to enterprise surrogate keys."""
    dimension_name: str
    mappings: List[Dict[str, Any]] = Field(default_factory=list)
    total_members: int = 0
    overlap_count: int = 0
    unique_per_system: Dict[str, int] = Field(default_factory=dict)


# ---------------------------------------------------------------------------
# Enterprise bus matrix
# ---------------------------------------------------------------------------

class EnterpriseBusMatrixEntry(BaseModel):
    """One row of the enterprise bus matrix."""
    fact_table: str
    source_systems: List[str] = Field(default_factory=list)
    grain: GrainLevel = GrainLevel.MONTHLY
    dimensions: Dict[str, bool] = Field(default_factory=dict)
    conformance_score: float = Field(ge=0.0, le=1.0, default=0.0)


class EnterpriseBusMatrix(BaseModel):
    """Full enterprise bus matrix."""
    matrix_id: str = Field(default_factory=lambda: _new_id("ebm"))
    entries: List[EnterpriseBusMatrixEntry] = Field(default_factory=list)
    all_dimensions: List[str] = Field(default_factory=list)
    all_systems: List[str] = Field(default_factory=list)
    overall_conformance: float = Field(ge=0.0, le=1.0, default=0.0)


# ---------------------------------------------------------------------------
# Cross-grain validation
# ---------------------------------------------------------------------------

class CrossGrainStatus(str, Enum):
    PASS = "pass"
    FAIL = "fail"
    WARN = "warn"


class CrossGrainValidation(BaseModel):
    """Result of cross-grain aggregation validation."""
    validation_id: str = Field(default_factory=lambda: _new_id("cgv"))
    fact_table: str = ""
    fine_grain: GrainLevel = GrainLevel.DAILY
    coarse_grain: GrainLevel = GrainLevel.MONTHLY
    measure: str = ""
    fine_total: float = 0.0
    coarse_total: float = 0.0
    difference: float = 0.0
    difference_pct: float = 0.0
    status: CrossGrainStatus = CrossGrainStatus.PASS
    threshold_pct: float = 0.01


# ---------------------------------------------------------------------------
# Enterprise schema
# ---------------------------------------------------------------------------

class EnterpriseSchema(BaseModel):
    """Complete enterprise schema definition."""
    schema_id: str = Field(default_factory=lambda: _new_id("esc"))
    name: str = ""
    facts: List[FactAlignment] = Field(default_factory=list)
    dimensions: List[ConformedDimension] = Field(default_factory=list)
    bus_matrix: Optional[EnterpriseBusMatrix] = None
    ddl_statements: List[str] = Field(default_factory=list)
    source_systems: List[str] = Field(default_factory=list)
