"""Atomic Azure acquisition journal and reporting-day replacement.

A single InnoDB row serializes publishers. A source revision in each downstream
marker prevents an older extraction from overwriting a newer materialization.
No change to DataBatchJob's protocol, no cross-database DET success lookup.
"""

from __future__ import annotations

from collections.abc import Sequence
from datetime import UTC, date, datetime

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

from finops_batches.domain.models import Record
from finops_batches.infrastructure.sponsorship_usage_gold_loader import (
    AzureSponsorshipUsageGoldLoader,
)

MARKER = "_azure_snapshot"


class SnapshotJournal:
    def __init__(self, engine: Engine) -> None:
        metadata = MetaData()
        self.state = Table(
            "azure_sponsorship_pipeline_state", metadata, autoload_with=engine
        )
        self.snapshots = Table(
            "azure_sponsorship_snapshot", metadata, autoload_with=engine
        )
        self.dirty = Table(
            "azure_sponsorship_gold_refresh_day", metadata, autoload_with=engine
        )

    def revision(self, connection: Connection, *, lock: bool = False) -> int:
        statement = select(self.state.c.revision).where(self.state.c.id == 1)
        if lock:
            statement = statement.with_for_update()
        value = connection.execute(statement).scalar_one_or_none()
        if value is None:
            raise ValueError("AZURE_SNAPSHOT_SCHEMA: apply migration 047")
        return int(value)

    def require(self, connection: Connection, stage: str, day: date) -> None:
        latest = connection.execute(
            select(func.max(self.snapshots.c.revision)).where(
                self.snapshots.c.stage == stage, self.snapshots.c.business_date == day
            )
        ).scalar_one()
        if latest is None:
            raise ValueError(f"AZURE_SNAPSHOT_MISSING: replay {stage} for {day}")
        previous = {"USAGE": "BRONZE", "FOCUS": "USAGE"}.get(stage)
        if previous:
            self.require(connection, previous, day)
            upstream = connection.execute(
                select(func.max(self.snapshots.c.revision)).where(
                    self.snapshots.c.stage == previous,
                    self.snapshots.c.business_date == day,
                )
            ).scalar_one()
            if latest < upstream:
                raise ValueError(f"AZURE_SNAPSHOT_OUTDATED: replay {stage} for {day}")

    def publish(
        self, connection: Connection, marker: Record, count: int, revision: int
    ) -> None:
        run = marker.get("ingestion_run_id")
        if not isinstance(run, str) or not run:
            raise ValueError("AZURE_SNAPSHOT_RUN_REQUIRED: use DataBatchJob")
        connection.execute(
            self.snapshots.insert().values(
                revision=revision + 1,
                stage=marker[MARKER],
                business_date=marker["business_date"],
                scope_id=marker.get("scope_id", ""),
                ingestion_run_id=run,
                row_count=count,
                published_at=datetime.now(UTC).replace(tzinfo=None),
            )
        )
        connection.execute(
            self.state.update()
            .where(self.state.c.id == 1)
            .values(revision=revision + 1)
        )


def snapshot_marker(
    stage: str, day: date, revision: int | None = None, **extra: object
) -> Record:
    return {
        MARKER: stage,
        "business_date": day,
        "source_revision": revision,
        "ingestion_run_id": None,
        **extra,
    }


def split_snapshot(
    records: Sequence[Record], stage: str
) -> tuple[Record, list[Record]]:
    if not records or records[0].get(MARKER) != stage:
        raise ValueError("AZURE_SNAPSHOT_MARKER_REQUIRED")
    marker, rows = dict(records[0]), [dict(row) for row in records[1:]]
    day = marker.get("business_date")
    if not isinstance(day, date) or isinstance(day, datetime):
        raise TypeError("AZURE_SNAPSHOT_INVALID_DAY")
    if any(MARKER in row or row.get("business_date") != day for row in rows):
        raise ValueError("AZURE_SNAPSHOT_MIXED_DAYS")
    return marker, rows


class AzureSnapshotLoader:
    """BRONZE append or USAGE/FOCUS replace; publish the journal atomically."""

    def __init__(self, *, database_url: str, table_name: str, stage: str) -> None:
        if stage not in {"BRONZE", "USAGE", "FOCUS"}:
            raise ValueError("AZURE_SNAPSHOT_INVALID_STAGE")
        self.stage = stage
        self._engine = create_engine(database_url, pool_pre_ping=True)
        try:
            self.table = Table(table_name, MetaData(), autoload_with=self._engine)
            self.journal = SnapshotJournal(self._engine)
        except Exception:
            self._engine.dispose()
            raise

    def load(self, records: Sequence[Record]) -> int:
        marker, rows = split_snapshot(records, self.stage)
        day = marker["business_date"]
        if self.stage == "BRONZE" and (
            not marker.get("scope_id")
            or any(
                row.get("scope_id") != marker["scope_id"]
                or row.get("ingestion_run_id") != marker.get("ingestion_run_id")
                for row in rows
            )
        ):
            raise ValueError("AZURE_SNAPSHOT_SCOPE_OR_RUN_MISMATCH")
        with self._engine.begin() as connection:
            revision = self.journal.revision(connection, lock=True)
            if self.stage != "BRONZE" and marker.get("source_revision") != revision:
                raise ValueError("AZURE_SNAPSHOT_STALE: source changed; retry the job")
            predicate = self.table.c.business_date == day
            if self.stage == "FOCUS":
                # Keep the union forever: a failed/missed Gold run can safely retry.
                dates = {
                    value.date()
                    for value in connection.execute(
                        select(self.table.c.ChargePeriodStart).where(predicate)
                    ).scalars()
                    if isinstance(value, datetime)
                }
                for row in rows:
                    value = row.get("ChargePeriodStart")
                    if not isinstance(value, datetime):
                        raise TypeError("AZURE_FOCUS_USAGE_DATE_REQUIRED")
                    dates.add(value.date())
                known = set(
                    connection.execute(
                        select(self.journal.dirty.c.usage_date).where(
                            self.journal.dirty.c.business_date == day
                        )
                    ).scalars()
                )
                for value in sorted(dates - known):
                    connection.execute(
                        self.journal.dirty.insert().values(
                            business_date=day, usage_date=value
                        )
                    )
            if self.stage != "BRONZE":
                connection.execute(delete(self.table).where(predicate))
            if rows:
                connection.execute(self.table.insert(), rows)
            self.journal.publish(connection, marker, len(rows), revision)
        return len(rows)

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


class AzureSnapshotGoldLoader(AzureSponsorshipUsageGoldLoader):
    def load(self, records: Sequence[Record]) -> int:
        if not records or records[0].get(MARKER) != "GOLD":
            raise ValueError("AZURE_SNAPSHOT_MARKER_REQUIRED")
        marker, rows = dict(records[0]), list(records[1:])
        raw_days = marker.get("usage_days")
        if (
            not isinstance(raw_days, list)
            or not raw_days
            or any(
                not isinstance(day, date) or isinstance(day, datetime)
                for day in raw_days
            )
        ):
            raise ValueError("AZURE_GOLD_TARGET_DAYS_REQUIRED")
        days = {day for day in raw_days if isinstance(day, date)}
        if any(MARKER in row or row.get("business_date") not in days for row in rows):
            raise ValueError("AZURE_GOLD_UNEXPECTED_DAY")
        journal = SnapshotJournal(self._engine)
        with self._engine.begin() as connection:
            revision = journal.revision(connection, lock=True)
            if marker.get("source_revision") != revision:
                raise ValueError("AZURE_SNAPSHOT_STALE: source changed; retry Gold")
            count = self._replace(connection, rows, days)
            journal.publish(connection, marker, count, revision)
        return count
