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 AzureRetailPricesSilverTransformer:
    """Normalize one RAW Azure Retail Prices item into provider Silver.

    v3 separates three concepts:

    - price_key: identity of one provider pricing version;
    - pricing_hash: economic content of that version;
    - source_hash: exact RAW provider payload for lineage.

    Descriptive labels (meter_name, product_name, sku_name, service_name,
    service_family) are deliberately excluded from pricing_hash. A label
    correction by Azure must not be treated as a retroactive price mutation.
    """

    NORMALIZATION_VERSION = "azure-retail-prices-v3"

    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",
        )

        observed_at = cls._datetime_from_db(
            bronze.get("source_ingestion_time"),
            "source_ingestion_time",
        )

        effective_start_date = cls._datetime(
            cls._pick(
                payload,
                "effectiveStartDate",
                "EffectiveStartDate",
            ),
            "effectiveStartDate",
        )

        meter_id = cls._required_string(
            cls._pick(
                payload,
                "meterId",
                "MeterId",
            ),
            "meterId",
        )

        currency_code = cls._required_string(
            cls._pick(
                payload,
                "currencyCode",
                "CurrencyCode",
            ),
            "currencyCode",
        ).upper()

        tier_minimum_units = cls._decimal(
            cls._pick(
                payload,
                "tierMinimumUnits",
                "TierMinimumUnits",
            )
        )
        if tier_minimum_units is None:
            tier_minimum_units = Decimal(0)

        retail_price = cls._required_decimal(
            cls._pick(
                payload,
                "retailPrice",
                "RetailPrice",
            ),
            "retailPrice",
        )

        unit_price = cls._required_decimal(
            cls._pick(
                payload,
                "unitPrice",
                "UnitPrice",
            ),
            "unitPrice",
        )

        product_id = cls._optional_string(
            cls._pick(
                payload,
                "productId",
                "ProductId",
            )
        )
        sku_id = cls._optional_string(
            cls._pick(
                payload,
                "skuId",
                "SkuId",
            )
        )
        service_id = cls._optional_string(
            cls._pick(
                payload,
                "serviceId",
                "ServiceId",
            )
        )
        arm_region_name = cls._optional_string(
            cls._pick(
                payload,
                "armRegionName",
                "ArmRegionName",
            )
        )
        location = cls._optional_string(
            cls._pick(
                payload,
                "location",
                "Location",
            )
        )
        api_type = cls._optional_string(
            cls._pick(
                payload,
                "type",
                "Type",
            )
        )
        reservation_term = cls._optional_string(
            cls._pick(
                payload,
                "reservationTerm",
                "ReservationTerm",
            )
        )
        unit_of_measure = cls._optional_string(
            cls._pick(
                payload,
                "unitOfMeasure",
                "UnitOfMeasure",
            )
        )
        arm_sku_name = cls._optional_string(
            cls._pick(
                payload,
                "armSkuName",
                "ArmSkuName",
            )
        )
        is_primary_meter_region = cls._bool(
            cls._pick(
                payload,
                "isPrimaryMeterRegion",
                "IsPrimaryMeterRegion",
            )
        )

        # Identity of one Azure pricing version.
        #
        # This contains stable identifiers and dimensions that can legitimately
        # distinguish two simultaneous price rows. Descriptive labels and the
        # price amounts themselves are not part of the identity.
        key_material: dict[str, object] = {
            "currency_code": currency_code,
            "meter_id": meter_id,
            "product_id": product_id,
            "sku_id": sku_id,
            "service_id": service_id,
            "arm_region_name": arm_region_name,
            "location": location,
            "api_type": api_type,
            "reservation_term": reservation_term,
            "unit_of_measure": unit_of_measure,
            "arm_sku_name": arm_sku_name,
            "is_primary_meter_region": is_primary_meter_region,
            "effective_start_date": effective_start_date.isoformat(),
            "tier_minimum_units": str(tier_minimum_units),
        }
        price_key = cls._hash_mapping(key_material)

        # Economic content of the pricing version.
        #
        # Because all identifying dimensions are already represented by
        # price_key, a pricing mutation means that one of the actual amounts
        # changed for the same provider version.
        pricing_material: dict[str, object] = {
            "price_key": price_key,
            "retail_price": str(retail_price),
            "unit_price": str(unit_price),
        }
        pricing_hash = cls._hash_mapping(pricing_material)

        return cast(
            Record,
            {
                "price_key": price_key,
                "currency_code": currency_code,
                "tier_minimum_units": tier_minimum_units,
                "reservation_term": reservation_term,
                "retail_price": retail_price,
                "unit_price": unit_price,
                "arm_region_name": arm_region_name,
                "location": location,
                "effective_start_date": effective_start_date,
                "meter_id": meter_id,
                "meter_name": cls._optional_string(
                    cls._pick(
                        payload,
                        "meterName",
                        "MeterName",
                    )
                ),
                "product_id": product_id,
                "product_name": cls._optional_string(
                    cls._pick(
                        payload,
                        "productName",
                        "ProductName",
                    )
                ),
                "sku_id": sku_id,
                "sku_name": cls._optional_string(
                    cls._pick(
                        payload,
                        "skuName",
                        "SkuName",
                    )
                ),
                "service_name": cls._optional_string(
                    cls._pick(
                        payload,
                        "serviceName",
                        "ServiceName",
                    )
                ),
                "service_id": service_id,
                "service_family": cls._optional_string(
                    cls._pick(
                        payload,
                        "serviceFamily",
                        "ServiceFamily",
                    )
                ),
                "unit_of_measure": unit_of_measure,
                "api_type": api_type,
                "arm_sku_name": arm_sku_name,
                "is_primary_meter_region": is_primary_meter_region,
                "pricing_hash": pricing_hash,
                "source_hash": cls._required_string(
                    bronze.get("source_payload_hash"),
                    "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,
            },
        )

    @staticmethod
    def _hash_mapping(
        values: Mapping[str, object],
    ) -> str:
        canonical = json.dumps(
            values,
            sort_keys=True,
            separators=(",", ":"),
            ensure_ascii=False,
            default=str,
        )
        return hashlib.sha256(canonical.encode("utf-8")).hexdigest()

    @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.")

        raw_object = cast(
            dict[object, object],
            decoded,
        )

        result: dict[str, object] = {}

        for key, item_value in raw_object.items():
            if not isinstance(key, str):
                raise TypeError(f"Les clés de {field} doivent être des chaînes.")
            result[key] = item_value

        return result

    @staticmethod
    def _optional_string(
        value: object,
    ) -> str | None:
        if value is None:
            return None

        if isinstance(
            value,
            (
                str,
                int,
                float,
                Decimal,
                bool,
            ),
        ):
            normalized = str(value).strip()
            return normalized or None

        raise TypeError(
            f"Valeur Retail non convertible en chaîne: {type(value).__name__}."
        )

    @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.")

        if isinstance(value, Decimal):
            return value

        if not isinstance(
            value,
            (
                str,
                int,
                float,
            ),
        ):
            raise TypeError(f"{field} doit être numérique.")

        try:
            return Decimal(str(value))
        except InvalidOperation as exc:
            raise ValueError(f"{field} est invalide: {value!r}.") from exc

    @staticmethod
    def _bool(
        value: object,
    ) -> bool | None:
        if value is None:
            return None

        if isinstance(value, bool):
            return value

        if value in (0, 1):
            return bool(value)

        if isinstance(value, str):
            normalized = value.strip().casefold()

            if normalized in {
                "true",
                "1",
                "yes",
            }:
                return True

            if normalized in {
                "false",
                "0",
                "no",
            }:
                return False

        raise TypeError("isPrimaryMeterRegion doit être booléen.")

    @staticmethod
    def _datetime(
        value: object,
        field: str,
    ) -> datetime:
        if isinstance(value, datetime):
            return AzureRetailPricesSilverTransformer._db_datetime(value)

        if not isinstance(value, str) or not value.strip():
            raise ValueError(f"{field} est obligatoire.")

        return AzureRetailPricesSilverTransformer._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 AzureRetailPricesSilverTransformer._db_datetime(value)

    @staticmethod
    def _db_datetime(
        value: datetime,
    ) -> datetime:
        if value.tzinfo is None:
            return value

        return value.astimezone(UTC).replace(tzinfo=None)
