from __future__ import annotations

import json
from collections.abc import Sequence

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

from finops_batches.domain.models import Record


class AzureRetailPriceHistoryLoader:
    """Historized idempotent loader for Azure Retail Prices.

    A logical version is identified by price_key. If Azure returns the same
    logical version with a different payload hash, loading stops instead of
    rewriting pricing history silently.
    """

    def __init__(
        self,
        *,
        database_url: str,
        table_name: str = "azure_retail_prices_bronze",
    ) -> None:
        if not database_url.strip():
            raise ValueError("database_url 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

        affected = 0
        with self._engine.begin() as connection:
            for source_record in records:
                record = dict(source_record)
                price_key = record.get("price_key")
                source_hash = record.get("source_hash")
                if not isinstance(price_key, str) or not price_key:
                    raise ValueError("price_key est obligatoire.")
                if not isinstance(source_hash, str) or not source_hash:
                    raise ValueError("source_hash est obligatoire.")

                existing = (
                    connection.execute(
                        select(
                            self._table.c.source_hash,
                            self._table.c.first_seen_at,
                            self._table.c.raw_payload,
                        ).where(self._table.c.price_key == price_key)
                    )
                    .mappings()
                    .first()
                )

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

                if existing["source_hash"] != source_hash:
                    existing_payload = json.loads(str(existing["raw_payload"]))
                    incoming_payload = json.loads(str(record["raw_payload"]))

                    all_keys = sorted(set(existing_payload) | set(incoming_payload))

                    differences = {
                        key: {
                            "existing": existing_payload.get(key),
                            "incoming": incoming_payload.get(key),
                        }
                        for key in all_keys
                        if existing_payload.get(key) != incoming_payload.get(key)
                    }
                    raise ValueError(
                        "RETAIL_PRICE_RETROACTIVE_MUTATION: Azure a renvoyé un payload "
                        f"différent pour price_key={price_key} ,"
                        f"differences={json.dumps(differences, ensure_ascii=False, default=str)}."
                    )

                connection.execute(
                    self._table.update()
                    .where(self._table.c.price_key == price_key)
                    .values(
                        last_seen_at=record["last_seen_at"],
                        ingestion_run_id=record.get("ingestion_run_id"),
                    )
                )
                affected += 1

        return affected

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