"""Daily SKU aggregates from Sponsorship FOCUS, including late acquisitions."""

from __future__ import annotations

import hashlib
import json
from collections.abc import Mapping, Sequence
from datetime import UTC, date, datetime, time, timedelta
from decimal import Decimal, localcontext

from sqlalchemy import MetaData, Table, and_, create_engine, func, or_, select
from sqlalchemy.engine import Engine
from sqlalchemy.sql import ColumnElement

from finops_batches.domain.models import BatchExecutionContext, Record

# Order is part of the hash contract. Names, never amounts, are dimensions.
GOLD_DIMENSIONS = (
    "billing_account_id",
    "subscription_id",
    "provider",
    "billing_model",
    "billing_currency",
    "charge_category",
    "charge_class",
    "charge_frequency",
    "sku_key",
    "sku_id",
    "meter_id",
    "region",
    "consumed_unit",
    "pricing_unit",
    "pricing_source",
    "pricing_confidence",
    "valuation_currency",
    "billed_cost_basis",
    "rating_reconciliation_status",
    "focus_compliance_status",
)
GOLD_LABELS = (
    "subscription_name",
    "service_name",
    "service_category",
    "sku_name",
    "meter_name",
)
GOLD_AMOUNTS = (
    "consumed_quantity",
    "pricing_quantity",
    "billed_cost",
    "effective_cost",
    "contracted_cost",
    "list_cost",
    "contracted_valued_cost",
    "retail_fallback_cost",
    "valued_cost",
)
GOLD_COUNTS = (
    "source_line_count",
    "valued_line_count",
    "unpriced_line_count",
    "billed_line_count",
    "effective_line_count",
    "currency_rejected_line_count",
)
SILVER_COLUMNS = (
    "business_date",
    "ChargePeriodStart",
    "ChargePeriodEnd",
    "BillingAccountId",
    "SubAccountId",
    "SubAccountName",
    "x_Provider",
    "x_BillingModel",
    "BillingCurrency",
    "ChargeCategory",
    "ChargeClass",
    "ChargeFrequency",
    "SkuId",
    "SkuMeter",
    "x_UsageMeterId",
    "x_SkuMeterId",
    "x_UsageMeterName",
    "RegionId",
    "RegionName",
    "ConsumedUnit",
    "PricingUnit",
    "x_PricingSource",
    "x_PricingConfidence",
    "x_RateCardCurrency",
    "x_RetailCurrency",
    "PricingCurrency",
    "ServiceName",
    "ServiceCategory",
    "ConsumedQuantity",
    "PricingQuantity",
    "BilledCost",
    "EffectiveCost",
    "ContractedCost",
    "ListCost",
    "x_GeneratedAt",
    "x_BilledCostBasis",
    "x_RatingReconciliationStatus",
    "x_FocusComplianceStatus",
)


def database_datetime(value: object, field: str) -> datetime:
    """Return UTC without timezone, as stored in the MariaDB DATETIME columns."""
    if not isinstance(value, datetime):
        raise TypeError(f"{field} doit être datetime.")
    if value.tzinfo is not None:
        return value.astimezone(UTC).replace(tzinfo=None)
    return value


def business_day(value: object) -> date:
    """Decode a date from reflected SQL DATE or a SQL DATE() result."""
    if isinstance(value, datetime):
        return database_datetime(value, "date").date()
    if isinstance(value, date):
        return value
    if isinstance(value, str):
        return date.fromisoformat(value)
    raise TypeError("Date métier invalide.")


def decimal_or_none(value: object) -> Decimal | None:
    """Keep accounting values exact; do not accept binary float input."""
    if value is None:
        return None
    if isinstance(value, bool) or not isinstance(value, (Decimal, int, str)):
        raise TypeError("Montant ou quantité attendu en Decimal, int ou chaîne.")
    number = Decimal(value)
    if not number.is_finite():
        raise ValueError("Montant ou quantité non fini.")
    return number


def string(value: object) -> str:
    """Normalize absent text consistently for grouping and SQL keys."""
    return "" if value is None else str(value).strip()


class AzureSponsorshipUsageGoldExtractor:
    """Read complete usage days affected by one acquisition day.

    Include the context day to support an explicit replay by usage date.
    Reading every acquisition for an affected day avoids overwriting a full
    aggregate with only the newly arrived fraction of its consumption.
    """

    def __init__(
        self, *, database_url: str, table_name: str = "azure_sponsorship_focus_silver"
    ) -> 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)
            missing = sorted(set(SILVER_COLUMNS) - set(self._table.c.keys()))
            if missing:
                raise ValueError("Colonnes Silver absentes : " + ", ".join(missing))
        except Exception:
            self._engine.dispose()
            raise

    def extract(self, context: BatchExecutionContext) -> list[Record]:
        """Read the impacted days from one consistent database read transaction."""
        table = self._table
        with self._engine.connect() as connection:
            acquisitions = connection.execute(
                select(func.date(table.c.ChargePeriodStart))
                .where(table.c.business_date == context.business_date)
                .distinct()
            ).scalars()
            days = {
                context.business_date,
                *(business_day(value) for value in acquisitions),
            }
            predicates: list[ColumnElement[bool]] = []
            for day in sorted(days):
                start = datetime.combine(day, time.min)
                predicates.append(
                    and_(
                        table.c.ChargePeriodStart >= start,
                        table.c.ChargePeriodStart < start + timedelta(days=1),
                    )
                )
            rows = connection.execute(
                select(*(table.c[name] for name in SILVER_COLUMNS)).where(
                    or_(*predicates)
                )
            ).mappings()
            result: list[Record] = []
            for row in rows:
                record: Record = dict(row)
                record["_gold_trigger_business_date"] = context.business_date
                result.append(record)
            return result

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


class AzureSponsorshipUsageGoldTransformer:
    """Aggregate existing Silver amounts without rerating or rounding them."""

    def transform(self, records: Sequence[Record]) -> list[Record]:
        """Group by usage day and dimensions with sufficient Decimal precision."""
        grouped: dict[tuple[date, tuple[str, ...]], Record] = {}
        with localcontext() as precision:
            precision.prec = 60
            for source in records:
                self._accumulate(grouped, source)
        return [grouped[key] for key in sorted(grouped)]

    def _accumulate(
        self,
        grouped: dict[tuple[date, tuple[str, ...]], Record],
        source: Mapping[str, object],
    ) -> None:
        start = database_datetime(source.get("ChargePeriodStart"), "ChargePeriodStart")
        end = database_datetime(source.get("ChargePeriodEnd"), "ChargePeriodEnd")
        day = start.date()
        if end <= start or end > datetime.combine(day + timedelta(days=1), time.min):
            raise ValueError(
                "GOLD_NON_DAILY_USAGE: période non journalière; répartition nécessaire."
            )
        acquired = business_day(source.get("business_date"))
        trigger = business_day(source.get("_gold_trigger_business_date"))
        generated = database_datetime(source.get("x_GeneratedAt"), "x_GeneratedAt")
        dimensions = self._dimensions(source)
        key = day, tuple(dimensions[name] for name in GOLD_DIMENSIONS)
        row: Record | None = grouped.get(key)
        if row is None:
            row = {
                "business_date": day,
                "grain_hash": hashlib.sha256(
                    json.dumps(
                        key[1], ensure_ascii=False, separators=(",", ":")
                    ).encode("utf-8")
                ).hexdigest(),
                **dimensions,
                **{name: "" for name in GOLD_LABELS},
                **{name: None for name in GOLD_AMOUNTS},
                **{name: 0 for name in GOLD_COUNTS},
                "source_business_date_min": acquired,
                "source_business_date_max": acquired,
                "trigger_business_date": trigger,
                "source_generated_at_max": generated,
                "generated_at": datetime.now(UTC).replace(tzinfo=None),
                # DataBatchJob fills this using BatchExecutionContext.logical_run_id.
                "ingestion_run_id": None,
            }
            grouped[key] = row
        elif row["trigger_business_date"] != trigger:
            raise ValueError(
                "GOLD_MULTIPLE_CONTEXTS: plusieurs contextes dans un même lot."
            )
        labels = {
            "subscription_name": string(source.get("SubAccountName")),
            "service_name": string(source.get("ServiceName")),
            "service_category": string(source.get("ServiceCategory")),
            # SkuId is the UsageAggregates meter in the supplied Silver transformer.
            "sku_name": string(source.get("SkuMeter"))
            or string(source.get("x_UsageMeterName")),
            "meter_name": string(source.get("x_UsageMeterName"))
            or string(source.get("SkuMeter")),
        }
        for name, value in labels.items():
            row[name] = max(string(row[name]), value)
        row["source_business_date_min"] = min(
            business_day(row["source_business_date_min"]), acquired
        )
        row["source_business_date_max"] = max(
            business_day(row["source_business_date_max"]), acquired
        )
        row["source_generated_at_max"] = max(
            database_datetime(
                row["source_generated_at_max"], "source_generated_at_max"
            ),
            generated,
        )
        for target, origin in (
            ("consumed_quantity", "ConsumedQuantity"),
            ("pricing_quantity", "PricingQuantity"),
            ("billed_cost", "BilledCost"),
            ("effective_cost", "EffectiveCost"),
            ("contracted_cost", "ContractedCost"),
            ("list_cost", "ListCost"),
        ):
            amount = decimal_or_none(source.get(origin))
            if target == "consumed_quantity" and amount is None:
                raise ValueError("ConsumedQuantity est obligatoire.")
            self._add(row, target, amount)
        pricing_source = dimensions["pricing_source"]
        candidate = (
            decimal_or_none(source.get("ContractedCost"))
            if pricing_source == "SPONSORSHIP_RATE_CARD"
            else (
                decimal_or_none(source.get("ListCost"))
                if pricing_source == "RETAIL_PRICE_FALLBACK"
                else None
            )
        )
        compatible = bool(dimensions["valuation_currency"]) and (
            dimensions["valuation_currency"] == dimensions["billing_currency"]
        )
        selected = candidate if compatible else None
        self._add(row, "valued_cost", selected)
        if pricing_source == "SPONSORSHIP_RATE_CARD":
            self._add(row, "contracted_valued_cost", selected)
        elif pricing_source == "RETAIL_PRICE_FALLBACK":
            self._add(row, "retail_fallback_cost", selected)
        for name, increment in (
            ("source_line_count", 1),
            ("valued_line_count", int(selected is not None)),
            ("unpriced_line_count", int(selected is None)),
            ("billed_line_count", int(source.get("BilledCost") is not None)),
            ("effective_line_count", int(source.get("EffectiveCost") is not None)),
            (
                "currency_rejected_line_count",
                int(candidate is not None and not compatible),
            ),
        ):
            count_value = row[name]
            if not isinstance(count_value, int):
                raise TypeError("Compteur Gold invalide.")
            row[name] = count_value + increment

    @staticmethod
    def _add(row: Record, name: str, amount: Decimal | None) -> None:
        if amount is not None:
            row[name] = (decimal_or_none(row[name]) or Decimal(0)) + amount

    @staticmethod
    def _dimensions(source: Mapping[str, object]) -> dict[str, str]:
        sku_id = string(source.get("SkuId"))
        meter_id = string(source.get("x_UsageMeterId")) or string(
            source.get("x_SkuMeterId")
        )
        if not meter_id:
            raise ValueError("Identité meter absente du Silver.")
        pricing_source = string(source.get("x_PricingSource")) or "UNKNOWN"
        currency_column = (
            "x_RateCardCurrency"
            if pricing_source == "SPONSORSHIP_RATE_CARD"
            else "x_RetailCurrency"
            if pricing_source == "RETAIL_PRICE_FALLBACK"
            else ""
        )
        valuation_currency = (
            string(source.get(currency_column)) or string(source.get("PricingCurrency"))
            if currency_column
            else ""
        )
        result = {
            "billing_account_id": string(source.get("BillingAccountId")),
            "subscription_id": string(source.get("SubAccountId")),
            "provider": string(source.get("x_Provider")),
            "billing_model": string(source.get("x_BillingModel")),
            "billing_currency": string(source.get("BillingCurrency")).upper(),
            "charge_category": string(source.get("ChargeCategory")),
            "charge_class": string(source.get("ChargeClass")),
            "charge_frequency": string(source.get("ChargeFrequency")),
            "sku_key": f"SKU:{sku_id}" if sku_id else f"METER:{meter_id}",
            "sku_id": sku_id,
            "meter_id": meter_id,
            "region": string(source.get("RegionId"))
            or string(source.get("RegionName")),
            "consumed_unit": string(source.get("ConsumedUnit")),
            "pricing_unit": string(source.get("PricingUnit")),
            "pricing_source": pricing_source,
            "pricing_confidence": string(source.get("x_PricingConfidence"))
            or "UNKNOWN",
            "valuation_currency": valuation_currency.upper(),
            "billed_cost_basis": string(source.get("x_BilledCostBasis")),
            "rating_reconciliation_status": string(
                source.get("x_RatingReconciliationStatus")
            ),
            "focus_compliance_status": string(source.get("x_FocusComplianceStatus")),
        }
        for required in ("billing_account_id", "subscription_id", "billing_currency"):
            if not result[required]:
                raise ValueError(f"Dimension Gold obligatoire : {required}.")
        return result
