from __future__ import annotations

from collections.abc import Sequence
from typing import cast

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

from finops_batches.domain.models import Record


class AzureRateCardHistoryLoader:
    """Historise les versions tarifaires sans écraser un ancien EffectiveDate.

    La contrainte unique de la table porte sur abonnement/offre/devise/région/meter/
    effective_date. Une ligne déjà connue ne modifie que last_seen_at et
    ingestion_run_id. Si Azure change rétroactivement le payload pour la même clé,
    le loader lève une erreur au lieu de masquer la mutation.
    """

    def __init__(self, *, database_url: str, table_name: str) -> None:
        if not database_url.strip():
            raise ValueError("database_url est obligatoire.")
        if not table_name.strip():
            raise ValueError("table_name est obligatoire.")

        self.engine: Engine = create_engine(database_url, pool_pre_ping=True)
        metadata = MetaData()
        self.table = Table(table_name, metadata, autoload_with=self.engine)

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

        inserted = 0
        with self.engine.begin() as connection:
            for raw_record in records:
                record = dict(raw_record)
                key_filter = (
                    (self.table.c.subscription_id == record["subscription_id"])
                    & (self.table.c.offer_durable_id == record["offer_durable_id"])
                    & (self.table.c.currency == record["currency"])
                    & (self.table.c.region_info == record["region_info"])
                    & (self.table.c.meter_id == record["meter_id"])
                    & (self.table.c.effective_date == record["effective_date"])
                )
                existing = (
                    connection.execute(
                        select(
                            self.table.c.source_hash,
                            self.table.c.last_seen_at,
                        ).where(key_filter)
                    )
                    .mappings()
                    .one_or_none()
                )

                if existing is None:
                    connection.execute(self.table.insert().values(**record))
                    inserted += 1
                    continue

                existing_hash = cast(str, existing["source_hash"])
                incoming_hash = cast(str, record["source_hash"])
                if existing_hash != incoming_hash:
                    raise ValueError(
                        "Mutation rétroactive Azure Rate Card détectée pour "
                        f"meter_id={record['meter_id']}, "
                        f"effective_date={record['effective_date']}. "
                        "Le payload existant n'a pas été écrasé."
                    )

                connection.execute(
                    self.table.update()
                    .where(key_filter)
                    .values(
                        last_seen_at=record["last_seen_at"],
                        ingestion_run_id=record.get("ingestion_run_id"),
                    )
                )

        return inserted

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