from __future__ import annotations

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 AzureSponsorshipFocusLoader:
    """Idempotent Silver loader keyed by RowId.

    A replay of the same usage row updates the Silver valuation. This is useful
    when historical Rate Card data is backfilled after the first Silver run.
    """

    def __init__(
        self,
        *,
        database_url: str,
        table_name: str = "azure_sponsorship_focus_silver",
    ) -> 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)
        if "RowId" not in self._table.c:
            raise ValueError(f"La table {table_name!r} doit contenir la colonne RowId.")

    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)
                row_id = record.get("RowId")
                if not isinstance(row_id, str) or not row_id.strip():
                    raise ValueError("RowId est obligatoire pour charger le Silver.")

                unknown_columns = sorted(set(record) - set(self._table.c.keys()))
                if unknown_columns:
                    raise ValueError(
                        "Colonnes absentes du DDL Silver : "
                        + ", ".join(unknown_columns)
                    )

                exists = connection.execute(
                    select(self._table.c.RowId).where(self._table.c.RowId == row_id)
                ).first()

                if exists is None:
                    connection.execute(self._table.insert().values(**record))
                else:
                    update_values = {
                        key: value for key, value in record.items() if key != "RowId"
                    }
                    connection.execute(
                        self._table.update()
                        .where(self._table.c.RowId == row_id)
                        .values(**update_values)
                    )
                affected += 1

        return affected

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