from __future__ import annotations

import hashlib
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 AzureSponsorshipRateCardTransformer:
    def transform(self, records: Sequence[Record]) -> list[Record]:
        return [self._transform_record(record) for record in records]

    @classmethod
    def _transform_record(cls, record: Record) -> Record:
        root = cast(Mapping[str, object], record)
        meter_id = cls._required_string(root.get("MeterId"), "MeterId")
        effective_date = cls._required_datetime(
            root.get("EffectiveDate"), "EffectiveDate"
        )
        rates = cls._rates(root.get("MeterRates"))
        rate_zero = rates.get(Decimal(0))
        if rate_zero is None:
            raise ValueError(
                f"Le meter {meter_id} ne contient pas de palier MeterRates['0']."
            )

        canonical_rates = {
            cls._decimal_to_json_key(threshold): str(rate)
            for threshold, rate in sorted(rates.items())
        }
        rates_json = json.dumps(
            canonical_rates,
            ensure_ascii=False,
            separators=(",", ":"),
            sort_keys=True,
        )

        raw_payload_dict = {
            key: value for key, value in root.items() if not key.startswith("_")
        }
        raw_payload = json.dumps(
            raw_payload_dict,
            ensure_ascii=False,
            separators=(",", ":"),
            sort_keys=True,
            default=str,
        )
        source_hash = hashlib.sha256(raw_payload.encode("utf-8")).hexdigest()

        retrieved_at = cls._required_datetime(
            root.get("_retrieved_at"), "_retrieved_at"
        )

        return {
            "subscription_id": cls._required_string(
                root.get("_subscription_id"), "_subscription_id"
            ),
            "offer_durable_id": cls._required_string(
                root.get("_offer_durable_id"), "_offer_durable_id"
            ),
            "currency": cls._required_string(root.get("_currency"), "_currency"),
            "locale": cls._required_string(root.get("_locale"), "_locale"),
            "region_info": cls._required_string(
                root.get("_region_info"), "_region_info"
            ),
            "meter_id": meter_id,
            "effective_date": effective_date,
            "included_quantity": cls._decimal(root.get("IncludedQuantity")),
            "meter_category": cls._string(root.get("MeterCategory")),
            "meter_sub_category": cls._string(root.get("MeterSubCategory")),
            "meter_name": cls._string(root.get("MeterName")),
            "meter_region": cls._string(root.get("MeterRegion")),
            "unit": cls._string(root.get("Unit")),
            "unit_price": rate_zero,
            "meter_rates_json": rates_json,
            "source_hash": source_hash,
            "raw_payload": raw_payload,
            "first_seen_at": retrieved_at,
            "last_seen_at": retrieved_at,
            "ingestion_run_id": cls._string(root.get("_ingestion_run_id")),
        }

    @staticmethod
    def _rates(value: object) -> dict[Decimal, Decimal]:
        if not isinstance(value, Mapping):
            raise TypeError("MeterRates doit être un objet JSON.")

        result: dict[Decimal, Decimal] = {}
        raw_mapping = cast(Mapping[object, object], value)
        for raw_threshold, raw_rate in raw_mapping.items():
            if not isinstance(raw_threshold, str):
                raise TypeError("Les clés de MeterRates doivent être des chaînes.")
            threshold = AzureSponsorshipRateCardTransformer._required_decimal(
                raw_threshold, "MeterRates.threshold"
            )
            rate = AzureSponsorshipRateCardTransformer._required_decimal(
                raw_rate, f"MeterRates[{raw_threshold!r}]"
            )
            result[threshold] = rate
        return result

    @staticmethod
    def _decimal_to_json_key(value: Decimal) -> str:
        normalized = value.normalize()
        return format(normalized, "f")

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

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

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

    @staticmethod
    def _required_decimal(value: object, field_name: str) -> Decimal:
        if isinstance(value, bool):
            raise TypeError(f"{field_name} ne peut pas être booléen.")
        if isinstance(value, Decimal):
            return value
        if isinstance(value, int):
            return Decimal(value)
        if isinstance(value, float):
            raw = str(value)
        elif isinstance(value, str):
            raw = value.strip()
        else:
            raise TypeError(f"{field_name} n'est pas numérique.")
        try:
            return Decimal(raw)
        except InvalidOperation as exc:
            raise ValueError(f"{field_name} est invalide : {value!r}.") from exc

    @staticmethod
    def _required_datetime(value: object, field_name: str) -> datetime:
        if isinstance(value, datetime):
            parsed = value
        elif isinstance(value, str):
            normalized = value.strip().replace("Z", "+00:00")
            try:
                parsed = datetime.fromisoformat(normalized)
            except ValueError as exc:
                raise ValueError(
                    f"{field_name} contient une date invalide : {value!r}."
                ) from exc
        else:
            raise TypeError(f"{field_name} doit être une date ISO ou datetime.")

        if parsed.tzinfo is None:
            return parsed
        return parsed.astimezone(UTC).replace(tzinfo=None)
