"""Atomic replacement of complete usage days affected by a Gold execution."""

from __future__ import annotations

from collections.abc import Sequence
from datetime import date

from sqlalchemy import MetaData, Table, create_engine, delete
from sqlalchemy.engine import Connection, Engine

from finops_batches.domain.models import Record
from finops_batches.providers.azure.sponsorship_usage_gold import (
    GOLD_AMOUNTS,
    GOLD_COUNTS,
    GOLD_DIMENSIONS,
    GOLD_LABELS,
    business_day,
)


class AzureSponsorshipUsageGoldLoader:
    """Replace several complete usage days in one InnoDB transaction.

    The standard single-day loader cannot handle late acquisitions affecting
    several usage days. No changes to the shared DataBatchJob protocol are needed.
    """

    def __init__(
        self, *, database_url: str, table_name: str = "azure_sponsorship_usage_gold"
    ) -> None:
        if not database_url.strip():
            raise ValueError("FINOPS_DATABASE_URL est obligatoire.")
        self._engine: Engine = create_engine(database_url, pool_pre_ping=True)
        try:
            self._table = Table(table_name, MetaData(), autoload_with=self._engine)
            required = {
                "business_date",
                "grain_hash",
                "ingestion_run_id",
                "source_business_date_min",
                "source_business_date_max",
                "trigger_business_date",
                "source_generated_at_max",
                "generated_at",
                *GOLD_DIMENSIONS,
                *GOLD_LABELS,
                *GOLD_AMOUNTS,
                *GOLD_COUNTS,
            }
            if not required <= set(self._table.c.keys()):
                raise ValueError(
                    "DDL Gold incompatible : appliquer 003_create_azure_sponsorship_usage_gold.sql."
                )
        except Exception:
            self._engine.dispose()
            raise

    def load(self, records: Sequence[Record]) -> int:
        """Validate the full payload before replacing any target data."""
        if not records:
            raise ValueError(
                "GOLD_EMPTY_DATASET: aucune date à remplacer; Gold conservé."
            )
        with self._engine.begin() as connection:
            return self._replace(connection, records, set())

    def _replace(
        self, connection: Connection, records: Sequence[Record], days: set[date]
    ) -> int:
        """A verified snapshot may explicitly replace days with no source rows."""
        keys: set[tuple[date, str]] = set()
        parameters: list[dict[str, object]] = []
        columns = set(self._table.c.keys())
        for record in records:
            unknown = sorted(set(record) - columns)
            if unknown:
                raise ValueError(
                    "Colonnes absentes du DDL Gold : " + ", ".join(unknown)
                )
            day = business_day(record.get("business_date"))
            key = record.get("grain_hash")
            if not isinstance(key, str) or len(key) != 64:
                raise ValueError("grain_hash invalide.")
            if (day, key) in keys:
                raise ValueError("GOLD_DUPLICATE_GRAIN: doublon de clé.")
            keys.add((day, key))
            run_id = record.get("ingestion_run_id")
            if not isinstance(run_id, str) or not run_id:
                raise ValueError("ingestion_run_id absent : utiliser DataBatchJob.")
            counts = [
                record.get(name)
                for name in (
                    "source_line_count",
                    "valued_line_count",
                    "unpriced_line_count",
                )
            ]
            if any(not isinstance(value, int) or value < 0 for value in counts):
                raise ValueError("Compteurs Gold invalides.")
            total, valued, unpriced = counts
            if (
                not isinstance(total, int)
                or not isinstance(valued, int)
                or not isinstance(unpriced, int)
            ):
                raise TypeError("Compteurs Gold invalides.")
            if total == 0 or total != valued + unpriced:
                raise ValueError(
                    "GOLD_LINE_RECONCILIATION_FAILED: volumes incohérents."
                )
            days.add(day)
            parameters.append(dict(record) | {"business_date": day})
        connection.execute(
            delete(self._table).where(self._table.c.business_date.in_(sorted(days)))
        )
        if parameters:
            connection.execute(self._table.insert(), parameters)
        return len(parameters)

    def close(self) -> None:
        """Release the connection pool."""
        self._engine.dispose()
