"""Journal-aware production adapters for the existing Azure transformations."""

from __future__ import annotations

from collections.abc import Sequence
from datetime import datetime, time, timedelta
from typing import Protocol

from sqlalchemy import and_, func, or_, select

from finops_batches.domain.models import BatchExecutionContext, Record
from finops_batches.infrastructure.azure_usage_snapshots import (
    MARKER,
    SnapshotJournal,
    snapshot_marker,
)
from finops_batches.providers.azure.sponsorship_billing import (
    AzureSponsorshipBillingExtractor,
)
from finops_batches.providers.azure.sponsorship_focus import (
    AzureSponsorshipFocusExtractor,
)
from finops_batches.providers.azure.sponsorship_usage_gold import (
    SILVER_COLUMNS,
    AzureSponsorshipUsageGoldExtractor,
    business_day,
)
from finops_batches.providers.azure.sponsorship_usage_silver import (
    AzureSponsorshipUsageBronzeExtractor,
)


class Transformer(Protocol):
    def transform(self, records: Sequence[Record]) -> list[Record]: ...


class SnapshotTransformer:
    """Carry a technical day marker through the unchanged business transformer."""

    def __init__(self, delegate: Transformer) -> None:
        self.delegate = delegate

    def transform(self, records: Sequence[Record]) -> list[Record]:
        if (
            not records
            or MARKER not in records[0]
            or any(MARKER in row for row in records[1:])
        ):
            raise ValueError("AZURE_SNAPSHOT_MARKER_REQUIRED")
        return [dict(records[0]), *self.delegate.transform(records[1:])]


class SnapshotBillingExtractor(AzureSponsorshipBillingExtractor):
    def extract(self, context: BatchExecutionContext) -> list[Record]:
        # The complete page iterator must finish before any snapshot is published.
        rows = super().extract(context)
        return [
            snapshot_marker(
                "BRONZE", context.business_date, scope_id=self.subscription_id
            ),
            *rows,
        ]


class SnapshotUsageExtractor(AzureSponsorshipUsageBronzeExtractor):
    def extract(self, context: BatchExecutionContext) -> list[Record]:
        journal = SnapshotJournal(self._engine)
        t, s = self._table, journal.snapshots
        newer = s.alias("newer")
        with self._engine.connect() as connection:
            revision = journal.revision(connection)
            snapshots = (
                connection.execute(
                    select(s).where(
                        s.c.stage == "BRONZE",
                        s.c.business_date == context.business_date,
                        ~select(newer.c.revision)
                        .where(
                            newer.c.stage == s.c.stage,
                            newer.c.business_date == s.c.business_date,
                            newer.c.scope_id == s.c.scope_id,
                            newer.c.revision > s.c.revision,
                        )
                        .exists(),
                    )
                )
                .mappings()
                .all()
            )
            if not snapshots:
                raise ValueError(
                    "AZURE_SNAPSHOT_MISSING: replay BRONZE for this reporting day"
                )
            scopes = set(
                connection.execute(
                    select(t.c.scope_id)
                    .where(t.c.business_date == context.business_date)
                    .distinct()
                ).scalars()
            )
            if not scopes <= {row["scope_id"] for row in snapshots}:
                raise ValueError(
                    "AZURE_SNAPSHOT_UNIDENTIFIED_SCOPE: reacquire or audit legacy Bronze"
                )
            result: list[Record] = [
                snapshot_marker("USAGE", context.business_date, revision)
            ]
            for snapshot in snapshots:
                rows = (
                    connection.execute(
                        select(
                            t.c.id.label("source_bronze_id"),
                            t.c.business_date,
                            t.c.payload,
                            t.c.source_hash.label("source_payload_hash"),
                            t.c.ingestion_run_id.label("source_ingestion_run_id"),
                            t.c.page_number,
                            t.c.source_record_number,
                            t.c.api_version,
                        )
                        .where(
                            t.c.business_date == context.business_date,
                            t.c.scope_id == snapshot["scope_id"],
                            t.c.ingestion_run_id == snapshot["ingestion_run_id"],
                        )
                        .order_by(t.c.page_number, t.c.source_record_number, t.c.id)
                    )
                    .mappings()
                    .all()
                )
                if len(rows) != snapshot["row_count"]:
                    raise ValueError(
                        "AZURE_SNAPSHOT_COUNT_MISMATCH: Bronze retained unchanged"
                    )
                result.extend(dict(row) for row in rows)
            return result


class SnapshotFocusExtractor(AzureSponsorshipFocusExtractor):
    def extract(self, context: BatchExecutionContext) -> list[Record]:
        journal = SnapshotJournal(self._engine)
        with self._engine.connect() as connection:
            revision = journal.revision(connection)
            journal.require(connection, "USAGE", context.business_date)
        return [
            snapshot_marker("FOCUS", context.business_date, revision),
            *super().extract(context),
        ]


class SnapshotGoldExtractor(AzureSponsorshipUsageGoldExtractor):
    def extract(self, context: BatchExecutionContext) -> list[Record]:
        journal = SnapshotJournal(self._engine)
        t = self._table
        with self._engine.connect() as connection:
            revision = journal.revision(connection)
            journal.require(connection, "FOCUS", context.business_date)
            old_days = connection.execute(
                select(journal.dirty.c.usage_date).where(
                    journal.dirty.c.business_date == context.business_date
                )
            ).scalars()
            current_days = connection.execute(
                select(func.date(t.c.ChargePeriodStart))
                .where(t.c.business_date == context.business_date)
                .distinct()
            ).scalars()
            days = {
                context.business_date,
                *(business_day(day) for day in old_days),
                *(business_day(day) for day in current_days),
            }
            predicates = []
            for day in sorted(days):
                start = datetime.combine(day, time.min)
                predicates.append(
                    and_(
                        t.c.ChargePeriodStart >= start,
                        t.c.ChargePeriodStart < start + timedelta(days=1),
                    )
                )
            rows = connection.execute(
                select(*(t.c[name] for name in SILVER_COLUMNS)).where(or_(*predicates))
            ).mappings()
            materialized = [dict(row) for row in rows]
            for source_day in {
                business_day(row["business_date"]) for row in materialized
            }:
                journal.require(connection, "FOCUS", source_day)
            return [
                snapshot_marker(
                    "GOLD", context.business_date, revision, usage_days=sorted(days)
                ),
                *(
                    dict(row) | {"_gold_trigger_business_date": context.business_date}
                    for row in materialized
                ),
            ]
