from __future__ import annotations

from collections.abc import Sequence
from typing import cast

from sqlalchemy import MetaData, Table, and_, create_engine, select, update
from sqlalchemy.engine import Engine

from finops_batches.domain.models import BatchExecutionContext, Record
from finops_batches.exceptions import BatchExecutionError


class PricingRawBronzeExtractor:
    """Read all RAW pricing objects collected for one business date."""

    def __init__(self, *, database_url: str, table_name: str) -> None:
        self._engine: Engine = create_engine(database_url, pool_pre_ping=True)
        metadata = MetaData()
        self._table = Table(table_name, metadata, autoload_with=self._engine)

        required = {
            "id",
            "business_date",
            "payload",
            "request_context",
            "source_hash",
            "ingestion_run_id",
            "ingestion_time",
            "page_number",
            "source_record_number",
        }
        missing = sorted(required.difference(self._table.c.keys()))
        if missing:
            raise ValueError(
                f"Colonnes RAW Bronze absentes de {table_name!r}: " + ", ".join(missing)
            )

    def extract(self, context: BatchExecutionContext) -> list[Record]:
        t = self._table

        statement = (
            select(
                t.c.id.label("source_bronze_id"),
                t.c.business_date,
                t.c.payload,
                t.c.request_context,
                t.c.source_hash.label("source_payload_hash"),
                t.c.ingestion_run_id.label("source_ingestion_run_id"),
                t.c.ingestion_time.label("source_ingestion_time"),
                t.c.page_number,
                t.c.source_record_number,
                t.c.api_version,
            )
            .where(t.c.business_date == context.business_date)
            .order_by(
                t.c.page_number,
                t.c.source_record_number,
                t.c.id,
            )
        )

        with self._engine.connect() as connection:
            return [
                cast(Record, dict(row))
                for row in connection.execute(statement).mappings()
            ]

    def close(self) -> None:
        self._engine.dispose()


class HistoricalPricingSilverLoader:
    """Upsert normalized historical pricing versions.

    ``source_hash`` identifies the exact RAW provider payload and is retained
    for lineage/audit.

    When the target Silver table exposes ``pricing_hash``, that semantic hash
    is used to detect a mutation of a known pricing version. This prevents a
    harmless change in the RAW payload from being interpreted as an economic
    price mutation.

    Tables without ``pricing_hash`` keep the historical behavior and use
    ``source_hash`` as the mutation hash. This preserves compatibility with the
    current Rate Card Silver implementation.
    """

    def __init__(
        self,
        *,
        database_url: str,
        table_name: str,
        natural_key: Sequence[str],
        mutation_error_code: str,
        mutation_hash_field: str | None = None,
    ) -> None:
        self._engine: Engine = create_engine(
            database_url,
            pool_pre_ping=True,
        )
        metadata = MetaData()
        self._table = Table(
            table_name,
            metadata,
            autoload_with=self._engine,
        )

        self._natural_key = tuple(natural_key)
        self._mutation_error_code = mutation_error_code

        if mutation_hash_field is not None:
            self._mutation_hash_field = mutation_hash_field
        elif "pricing_hash" in self._table.c:
            self._mutation_hash_field = "pricing_hash"
        else:
            self._mutation_hash_field = "source_hash"

        required = {
            *self._natural_key,
            "source_hash",
            "last_seen_at",
            self._mutation_hash_field,
        }
        missing = sorted(required.difference(self._table.c.keys()))
        if missing:
            raise ValueError(
                f"Colonnes Silver absentes de {table_name!r}: " + ", ".join(missing)
            )

    def load(self, records: Sequence[Record]) -> int:
        if not records:
            return 0

        processed = 0

        with self._engine.begin() as connection:
            for record in records:
                predicate = and_(
                    *[
                        self._table.c[name] == record.get(name)
                        for name in self._natural_key
                    ]
                )

                existing = (
                    connection.execute(
                        select(
                            self._table.c.id,
                            self._table.c.source_hash,
                            self._table.c[self._mutation_hash_field].label(
                                "mutation_hash"
                            ),
                        ).where(predicate)
                    )
                    .mappings()
                    .first()
                )

                if existing is None:
                    connection.execute(self._table.insert().values(dict(record)))
                    processed += 1
                    continue

                existing_mutation_hash = self._required_hash(
                    existing.get("mutation_hash"),
                    field_name=self._mutation_hash_field,
                )
                incoming_mutation_hash = self._required_hash(
                    record.get(self._mutation_hash_field),
                    field_name=self._mutation_hash_field,
                )

                if existing_mutation_hash != incoming_mutation_hash:
                    key_text = ", ".join(
                        f"{name}={record.get(name)!r}" for name in self._natural_key
                    )
                    raise BatchExecutionError(
                        f"{self._mutation_error_code}: mutation du contenu "
                        f"tarifaire pour une version déjà connue ({key_text}). "
                        f"hash_field={self._mutation_hash_field!r}, "
                        f"existing_hash={existing_mutation_hash!r}, "
                        f"incoming_hash={incoming_mutation_hash!r}."
                    )

                # Same pricing version: refresh observation/lineage. The RAW
                # source hash may legitimately differ while pricing_hash stays
                # identical.
                refresh_fields = {
                    name: record.get(name)
                    for name in (
                        "source_hash",
                        "last_seen_at",
                        "source_bronze_id",
                        "source_ingestion_run_id",
                        "ingestion_run_id",
                        "normalization_version",
                        "normalized_at",
                    )
                    if name in self._table.c and name in record
                }

                if refresh_fields:
                    connection.execute(
                        update(self._table)
                        .where(self._table.c.id == existing["id"])
                        .values(**refresh_fields)
                    )

                processed += 1

        return processed

    def close(self) -> None:
        self._engine.dispose()

    @staticmethod
    def _required_hash(
        value: object,
        *,
        field_name: str,
    ) -> str:
        if not isinstance(value, str) or not value.strip():
            raise ValueError(f"Le champ de hash {field_name!r} est obligatoire.")
        return value.strip()
