from __future__ import annotations

from collections.abc import Sequence
from dataclasses import dataclass, field
from datetime import UTC, date, datetime
from decimal import Decimal
from hashlib import sha256
from typing import cast

from sqlalchemy import MetaData, Table, create_engine, select
from sqlalchemy.engine import Engine

from finops_batches.domain.models import BatchExecutionContext, Record


class GcpUsageGoldExtractor:
    """Read one business day from local GCP FOCUS Silver."""

    def __init__(
        self,
        *,
        database_url: str,
        table_name: str = "gcp_focus_silver",
    ) -> None:
        self._engine: Engine = create_engine(database_url, pool_pre_ping=True)
        metadata = MetaData()
        self._table = Table(table_name, metadata, autoload_with=self._engine)

        required = {
            "id",
            "business_date",
            "ServiceProviderName",
            "BillingAccountId",
            "BillingAccountName",
            "InvoiceIssuerName",
            "SubAccountId",
            "SubAccountName",
            "ServiceCategory",
            "ServiceName",
            "SkuId",
            "ChargeDescription",
            "RegionId",
            "RegionName",
            "BillingCurrency",
            "ConsumedQuantity",
            "ConsumedUnit",
            "ListCost",
            "ContractedCost",
            "BilledCost",
            "EffectiveCost",
            "ChargeCategory",
            "PricingCategory",
            "x_FocusConformanceStatus",
        }
        missing = sorted(required.difference(self._table.c.keys()))
        if missing:
            raise ValueError(
                f"Colonnes FOCUS Silver absentes de {table_name!r}: "
                + ", ".join(missing)
            )

    def extract(self, context: BatchExecutionContext) -> list[Record]:
        table = self._table
        statement = (
            select(
                table.c.id.label("source_focus_id"),
                table.c.business_date,
                table.c.ServiceProviderName,
                table.c.BillingAccountId,
                table.c.BillingAccountName,
                table.c.InvoiceIssuerName,
                table.c.SubAccountId,
                table.c.SubAccountName,
                table.c.ServiceCategory,
                table.c.ServiceName,
                table.c.SkuId,
                table.c.ChargeDescription,
                table.c.RegionId,
                table.c.RegionName,
                table.c.BillingCurrency,
                table.c.ConsumedQuantity,
                table.c.ConsumedUnit,
                table.c.ListCost,
                table.c.ContractedCost,
                table.c.BilledCost,
                table.c.EffectiveCost,
                table.c.ChargeCategory,
                table.c.PricingCategory,
                table.c.x_FocusConformanceStatus,
            )
            .where(table.c.business_date == context.business_date)
            .order_by(table.c.id)
        )

        with self._engine.connect() as connection:
            return [
                cast(Record, dict(row))
                for row in connection.execute(statement).mappings()
            ]

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


@dataclass(frozen=True, slots=True)
class GcpUsageGoldKey:
    business_date: date
    service_provider_name: str
    billing_account_id: str
    billing_account_name: str | None
    invoice_issuer_name: str | None
    project_id: str | None
    project_name: str | None
    service_category: str
    service_name: str
    sku_id: str | None
    sku_description: str | None
    region_id: str | None
    region_name: str | None
    billing_currency: str
    consumed_unit: str
    pricing_category: str


@dataclass(slots=True)
class GcpUsageGoldAccumulator:
    consumed_quantity: Decimal = field(default_factory=Decimal)
    list_cost: Decimal = field(default_factory=Decimal)
    contracted_cost: Decimal = field(default_factory=Decimal)
    billed_cost: Decimal = field(default_factory=Decimal)
    effective_cost: Decimal = field(default_factory=Decimal)
    credit_amount: Decimal = field(default_factory=Decimal)
    source_row_count: int = 0
    usage_row_count: int = 0
    tax_row_count: int = 0
    adjustment_row_count: int = 0
    standard_row_count: int = 0
    committed_row_count: int = 0
    valued_row_count: int = 0
    unpriced_row_count: int = 0
    conformance_ready_row_count: int = 0
    conformance_partial_row_count: int = 0


class GcpUsageGoldTransformer:
    """Aggregate GCP FOCUS Silver into a daily reporting Gold."""

    PROVIDER = "GCP"
    NORMALIZATION_VERSION = "gcp-usage-gold-v1"

    def transform(self, records: Sequence[Record]) -> list[Record]:
        built_at = datetime.now(UTC).replace(tzinfo=None)
        groups: dict[GcpUsageGoldKey, GcpUsageGoldAccumulator] = {}

        for record in records:
            key = self._key(record)
            accumulator = groups.setdefault(key, GcpUsageGoldAccumulator())
            self._accumulate(accumulator, record)

        return [
            self._to_record(key, accumulator, built_at=built_at)
            for key, accumulator in sorted(
                groups.items(),
                key=lambda item: self._sort_key(item[0]),
            )
        ]

    @classmethod
    def _key(cls, record: Record) -> GcpUsageGoldKey:
        return GcpUsageGoldKey(
            business_date=cls._required_date(
                record.get("business_date"), "business_date"
            ),
            service_provider_name=cls._required_string(
                record.get("ServiceProviderName"), "ServiceProviderName"
            ),
            billing_account_id=cls._required_string(
                record.get("BillingAccountId"), "BillingAccountId"
            ),
            billing_account_name=cls._optional_string(record.get("BillingAccountName")),
            invoice_issuer_name=cls._optional_string(record.get("InvoiceIssuerName")),
            project_id=cls._optional_string(record.get("SubAccountId")),
            project_name=cls._optional_string(record.get("SubAccountName")),
            service_category=cls._required_string(
                record.get("ServiceCategory"), "ServiceCategory"
            ),
            service_name=cls._required_string(record.get("ServiceName"), "ServiceName"),
            sku_id=cls._optional_string(record.get("SkuId")),
            sku_description=cls._optional_string(record.get("ChargeDescription")),
            region_id=cls._optional_string(record.get("RegionId")),
            region_name=cls._optional_string(record.get("RegionName")),
            billing_currency=cls._required_string(
                record.get("BillingCurrency"), "BillingCurrency"
            ),
            consumed_unit=cls._required_string(
                record.get("ConsumedUnit"), "ConsumedUnit"
            ),
            pricing_category=cls._required_string(
                record.get("PricingCategory"), "PricingCategory"
            ),
        )

    @classmethod
    def _accumulate(
        cls,
        accumulator: GcpUsageGoldAccumulator,
        record: Record,
    ) -> None:
        consumed_quantity = cls._decimal(record.get("ConsumedQuantity"))
        list_cost = cls._decimal(record.get("ListCost"))
        contracted_cost = cls._decimal(record.get("ContractedCost"))
        billed_cost = cls._decimal(record.get("BilledCost"))
        effective_cost = cls._decimal(record.get("EffectiveCost"))

        accumulator.consumed_quantity += consumed_quantity or Decimal(0)
        accumulator.list_cost += list_cost or Decimal(0)
        accumulator.contracted_cost += contracted_cost or Decimal(0)
        accumulator.billed_cost += billed_cost or Decimal(0)
        accumulator.effective_cost += effective_cost or Decimal(0)
        accumulator.credit_amount += (billed_cost or Decimal(0)) - (
            contracted_cost or Decimal(0)
        )
        accumulator.source_row_count += 1

        charge_category = cls._required_string(
            record.get("ChargeCategory"), "ChargeCategory"
        )
        if charge_category == "Usage":
            accumulator.usage_row_count += 1
        elif charge_category == "Tax":
            accumulator.tax_row_count += 1
        elif charge_category == "Adjustment":
            accumulator.adjustment_row_count += 1

        pricing_category = cls._required_string(
            record.get("PricingCategory"), "PricingCategory"
        )
        if pricing_category == "Committed":
            accumulator.committed_row_count += 1
        else:
            accumulator.standard_row_count += 1

        if effective_cost is None:
            accumulator.unpriced_row_count += 1
        else:
            accumulator.valued_row_count += 1

        conformance_status = cls._required_string(
            record.get("x_FocusConformanceStatus"),
            "x_FocusConformanceStatus",
        )
        if conformance_status == "READY_FOR_CONFORMANCE_REVIEW":
            accumulator.conformance_ready_row_count += 1
        else:
            accumulator.conformance_partial_row_count += 1

    @classmethod
    def _to_record(
        cls,
        key: GcpUsageGoldKey,
        accumulator: GcpUsageGoldAccumulator,
        *,
        built_at: datetime,
    ) -> Record:
        grain_key = cls._grain_key(key)
        return cast(
            Record,
            {
                "business_date": key.business_date,
                "grain_key": grain_key,
                "provider": cls.PROVIDER,
                "service_provider_name": key.service_provider_name,
                "billing_account_id": key.billing_account_id,
                "billing_account_name": key.billing_account_name,
                "invoice_issuer_name": key.invoice_issuer_name,
                "project_id": key.project_id,
                "project_name": key.project_name,
                "service_category": key.service_category,
                "service_name": key.service_name,
                "sku_id": key.sku_id,
                "sku_description": key.sku_description,
                "region_id": key.region_id,
                "region_name": key.region_name,
                "billing_currency": key.billing_currency,
                "consumed_unit": key.consumed_unit,
                "pricing_category": key.pricing_category,
                "consumed_quantity": accumulator.consumed_quantity,
                "list_cost": accumulator.list_cost,
                "contracted_cost": accumulator.contracted_cost,
                "billed_cost": accumulator.billed_cost,
                "effective_cost": accumulator.effective_cost,
                "credit_amount": accumulator.credit_amount,
                "source_row_count": accumulator.source_row_count,
                "usage_row_count": accumulator.usage_row_count,
                "tax_row_count": accumulator.tax_row_count,
                "adjustment_row_count": accumulator.adjustment_row_count,
                "standard_row_count": accumulator.standard_row_count,
                "committed_row_count": accumulator.committed_row_count,
                "valued_row_count": accumulator.valued_row_count,
                "unpriced_row_count": accumulator.unpriced_row_count,
                "conformance_ready_row_count": (
                    accumulator.conformance_ready_row_count
                ),
                "conformance_partial_row_count": (
                    accumulator.conformance_partial_row_count
                ),
                "normalization_version": cls.NORMALIZATION_VERSION,
                "built_at": built_at,
                "ingestion_run_id": None,
            },
        )

    @staticmethod
    def _sort_key(key: GcpUsageGoldKey) -> tuple[str, ...]:
        return (
            key.business_date.isoformat(),
            key.billing_account_id,
            key.project_id or "",
            key.service_category,
            key.service_name,
            key.sku_id or "",
            key.region_id or "",
            key.billing_currency,
            key.consumed_unit,
            key.pricing_category,
        )

    @staticmethod
    def _grain_key(key: GcpUsageGoldKey) -> str:
        values = (
            key.business_date.isoformat(),
            key.service_provider_name,
            key.billing_account_id,
            key.billing_account_name or "",
            key.invoice_issuer_name or "",
            key.project_id or "",
            key.project_name or "",
            key.service_category,
            key.service_name,
            key.sku_id or "",
            key.sku_description or "",
            key.region_id or "",
            key.region_name or "",
            key.billing_currency,
            key.consumed_unit,
            key.pricing_category,
        )
        return sha256("\x1f".join(values).encode()).hexdigest()

    @staticmethod
    def _required_date(value: object, field_name: str) -> date:
        if isinstance(value, datetime):
            return value.date()
        if isinstance(value, date):
            return value
        raise TypeError(f"{field_name} doit être une date.")

    @staticmethod
    def _optional_string(value: object) -> str | None:
        if value is None:
            return None
        if not isinstance(value, str):
            raise TypeError("La valeur doit être une chaîne ou None.")
        normalized = value.strip()
        return normalized or None

    @classmethod
    def _required_string(cls, value: object, field_name: str) -> str:
        result = cls._optional_string(value)
        if result is None:
            raise ValueError(f"{field_name} est obligatoire.")
        return result

    @staticmethod
    def _decimal(value: object) -> Decimal | None:
        if value is None:
            return None
        if isinstance(value, bool):
            raise TypeError("Une valeur booléenne n'est pas un Decimal valide.")
        if isinstance(value, Decimal):
            return value
        if isinstance(value, int):
            return Decimal(value)
        if isinstance(value, float):
            return Decimal(str(value))
        if isinstance(value, str):
            normalized = value.strip()
            if not normalized:
                return None
            return Decimal(normalized)
        raise TypeError(f"Valeur non convertible en Decimal: {type(value).__name__}.")
