from __future__ import annotations

import json
from collections.abc import Mapping, Sequence
from datetime import UTC, datetime
from decimal import Decimal, InvalidOperation
from typing import cast

from finops_batches.domain.models import Record


class AzureSponsorshipRateCardSilverTransformer:
    NORMALIZATION_VERSION = "azure-rate-card-v1"

    def transform(self, records: Sequence[Record]) -> list[Record]:
        normalized_at = self._db_datetime(datetime.now(UTC))
        return [self._transform_one(record, normalized_at) for record in records]

    @classmethod
    def _transform_one(cls, bronze: Record, normalized_at: datetime) -> Record:
        payload = cls._json_object(bronze.get("payload"), "payload")
        context = cls._json_object(bronze.get("request_context"), "request_context")
        meter_rates = cls._mapping_or_empty(
            cls._pick(payload, "MeterRates", "meterRates")
        )
        effective_date = cls._datetime(
            cls._pick(payload, "EffectiveDate", "effectiveDate"),
            "EffectiveDate",
        )
        meter_id = cls._required_string(
            cls._pick(payload, "MeterId", "meterId"), "MeterId"
        )
        observed_at = cls._datetime_from_db(
            bronze.get("source_ingestion_time"), "source_ingestion_time"
        )

        return cast(
            Record,
            {
                "subscription_id": cls._required_string(
                    context.get("subscription_id"), "subscription_id"
                ),
                "offer_durable_id": cls._required_string(
                    context.get("offer_durable_id"), "offer_durable_id"
                ),
                "currency": cls._required_string(
                    context.get("currency"), "currency"
                ).upper(),
                "locale": cls._optional_string(context.get("locale")),
                "region_info": cls._required_string(
                    context.get("region_info"), "region_info"
                ),
                "meter_id": meter_id,
                "effective_date": effective_date,
                "included_quantity": cls._decimal(
                    cls._pick(payload, "IncludedQuantity", "includedQuantity")
                ),
                "meter_category": cls._optional_string(
                    cls._pick(payload, "MeterCategory", "meterCategory")
                ),
                "meter_sub_category": cls._optional_string(
                    cls._pick(payload, "MeterSubCategory", "meterSubCategory")
                ),
                "meter_name": cls._optional_string(
                    cls._pick(payload, "MeterName", "meterName")
                ),
                "meter_region": cls._optional_string(
                    cls._pick(payload, "MeterRegion", "meterRegion")
                ),
                "unit": cls._optional_string(cls._pick(payload, "Unit", "unit")),
                "unit_price": cls._base_rate(meter_rates),
                "meter_rates_json": json.dumps(
                    meter_rates,
                    ensure_ascii=False,
                    separators=(",", ":"),
                    sort_keys=True,
                    default=str,
                ),
                "source_hash": bronze.get("source_payload_hash"),
                "first_seen_at": observed_at,
                "last_seen_at": observed_at,
                "source_bronze_id": bronze.get("source_bronze_id"),
                "source_ingestion_run_id": bronze.get("source_ingestion_run_id"),
                "ingestion_run_id": None,
                "normalization_version": cls.NORMALIZATION_VERSION,
                "normalized_at": normalized_at,
            },
        )

    @classmethod
    def _base_rate(cls, rates: Mapping[str, object]) -> Decimal:
        if not rates:
            raise ValueError("MeterRates est vide pour un meter Rate Card.")
        parsed: list[tuple[Decimal, Decimal]] = []
        for threshold_raw, rate_raw in rates.items():
            threshold = cls._required_decimal(threshold_raw, "MeterRates threshold")
            rate = cls._required_decimal(rate_raw, "MeterRates rate")
            parsed.append((threshold, rate))
        for threshold, rate in parsed:
            if threshold == 0:
                return rate
        return min(parsed, key=lambda item: item[0])[1]

    @staticmethod
    def _pick(values: Mapping[str, object], *names: str) -> object:
        for name in names:
            if name in values:
                return values[name]
        return None

    @staticmethod
    def _json_object(value: object, field: str) -> dict[str, object]:
        if not isinstance(value, str):
            raise TypeError(f"{field} doit être une chaîne JSON.")
        decoded: object = json.loads(value)
        if not isinstance(decoded, dict):
            raise TypeError(f"{field} doit contenir un objet JSON.")
        return cast(dict[str, object], decoded)

    @staticmethod
    def _mapping_or_empty(value: object) -> dict[str, object]:
        if value is None:
            return {}
        if not isinstance(value, dict):
            raise TypeError("MeterRates doit être un objet JSON.")
        result: dict[str, object] = {}
        for key, item in cast(dict[object, object], value).items():
            result[str(key)] = item
        return result

    @staticmethod
    def _optional_string(value: object) -> str | None:
        if value is None:
            return None
        value = str(value).strip()
        return value or None

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

    @classmethod
    def _decimal(cls, value: object) -> Decimal | None:
        if value is None:
            return None
        return cls._required_decimal(value, "decimal")

    @staticmethod
    def _required_decimal(value: object, field: str) -> Decimal:
        if value is None or isinstance(value, bool):
            raise ValueError(f"{field} est obligatoire et numérique.")
        try:
            return Decimal(str(value))
        except InvalidOperation as exc:
            raise ValueError(f"{field} est invalide: {value!r}.") from exc

    @staticmethod
    def _datetime(value: object, field: str) -> datetime:
        if isinstance(value, datetime):
            return AzureSponsorshipRateCardSilverTransformer._db_datetime(value)
        if not isinstance(value, str) or not value.strip():
            raise ValueError(f"{field} est obligatoire.")
        return AzureSponsorshipRateCardSilverTransformer._db_datetime(
            datetime.fromisoformat(value.strip())
        )

    @staticmethod
    def _datetime_from_db(value: object, field: str) -> datetime:
        if not isinstance(value, datetime):
            raise TypeError(f"{field} doit être un datetime.")
        return AzureSponsorshipRateCardSilverTransformer._db_datetime(value)

    @staticmethod
    def _db_datetime(value: datetime) -> datetime:
        if value.tzinfo is None:
            return value
        return value.astimezone(UTC).replace(tzinfo=None)
