from __future__ import annotations

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

from finops_batches.domain.models import Record


class AzureRetailPriceCatalogTransformer:
    """Normalize Azure Retail Prices records for Bronze persistence.

    ``price_key`` identifies one logical Retail price version. It deliberately
    excludes the actual price values so that a retroactive price mutation keeps
    the same identity and can be detected through ``source_hash``.

    ``source_hash`` is computed from normalized business fields, while
    ``raw_payload`` keeps the complete Azure payload for audit purposes.
    """

    def transform(self, records: Sequence[Record]) -> list[Record]:
        return [self._transform_record(record) for record in records]

    def _transform_record(self, record: Record) -> Record:
        meter_id = self._require_string(record.get("meterId"), "meterId")
        meter_name = self._optional_string(record.get("meterName")) or ""

        currency_code = self._require_string(
            record.get("currencyCode"), "currencyCode"
        ).upper()
        effective_start_date = self._parse_datetime(
            record.get("effectiveStartDate"), "effectiveStartDate"
        )
        retail_price = self._require_decimal(record.get("retailPrice"), "retailPrice")
        unit_price = self._require_decimal(record.get("unitPrice"), "unitPrice")
        tier_minimum_units = self._decimal_or_zero(record.get("tierMinimumUnits"))
        api_type = self._optional_string(record.get("type")) or "Consumption"
        retrieved_at = self._parse_datetime(
            record.get("_retrieved_at"), "_retrieved_at"
        )

        arm_region_name = self._optional_string(record.get("armRegionName")) or ""
        product_id = self._optional_string(record.get("productId")) or ""
        sku_id = self._optional_string(record.get("skuId")) or ""
        reservation_term = self._optional_string(record.get("reservationTerm")) or ""
        unit_of_measure = self._optional_string(record.get("unitOfMeasure")) or ""
        is_primary_meter_region = self._bool_or_none(record.get("isPrimaryMeterRegion"))

        location = self._optional_string(record.get("location"))
        product_name = self._optional_string(record.get("productName"))
        sku_name = self._optional_string(record.get("skuName"))
        service_name = self._optional_string(record.get("serviceName"))
        service_id = self._optional_string(record.get("serviceId"))
        service_family = self._optional_string(record.get("serviceFamily"))
        arm_sku_name = self._optional_string(record.get("armSkuName"))

        raw_payload = json.dumps(
            self._json_safe_source(record),
            ensure_ascii=False,
            sort_keys=True,
            separators=(",", ":"),
        )

        price_key = self._build_price_key(
            currency_code=currency_code,
            meter_id=meter_id,
            meter_name=meter_name,
            arm_region_name=arm_region_name,
            product_id=product_id,
            sku_id=sku_id,
            api_type=api_type,
            reservation_term=reservation_term,
            unit_of_measure=unit_of_measure,
            effective_start_date=effective_start_date,
            tier_minimum_units=tier_minimum_units,
            is_primary_meter_region=is_primary_meter_region,
        )

        source_hash = self._build_source_hash(
            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=meter_name,
            product_id=product_id,
            product_name=product_name,
            sku_id=sku_id,
            sku_name=sku_name,
            service_name=service_name,
            service_id=service_id,
            service_family=service_family,
            unit_of_measure=unit_of_measure,
            api_type=api_type,
            is_primary_meter_region=is_primary_meter_region,
            arm_sku_name=arm_sku_name,
        )

        return {
            "price_key": price_key,
            "currency_code": currency_code,
            "tier_minimum_units": tier_minimum_units,
            "reservation_term": reservation_term or None,
            "retail_price": retail_price,
            "unit_price": unit_price,
            "arm_region_name": arm_region_name,
            "location": location,
            "effective_start_date": self._to_database_datetime(effective_start_date),
            "meter_id": meter_id,
            "meter_name": meter_name or None,
            "product_id": product_id,
            "sku_id": sku_id,
            "product_name": product_name,
            "sku_name": sku_name,
            "service_name": service_name,
            "service_id": service_id,
            "service_family": service_family,
            "unit_of_measure": unit_of_measure or None,
            "api_type": api_type,
            "is_primary_meter_region": is_primary_meter_region,
            "arm_sku_name": arm_sku_name,
            "source_hash": source_hash,
            "raw_payload": raw_payload,
            "first_seen_at": self._to_database_datetime(retrieved_at),
            "last_seen_at": self._to_database_datetime(retrieved_at),
            "ingestion_run_id": self._optional_string(record.get("_ingestion_run_id")),
        }

    @staticmethod
    def _build_price_key(
        *,
        currency_code: str,
        meter_id: str,
        meter_name: str,
        arm_region_name: str,
        product_id: str,
        sku_id: str,
        api_type: str,
        reservation_term: str,
        unit_of_measure: str,
        effective_start_date: datetime,
        tier_minimum_units: Decimal,
        is_primary_meter_region: bool | None,
    ) -> str:
        key_payload: dict[str, object] = {
            "currency_code": currency_code,
            "meter_id": meter_id,
            "meter_name": meter_name,
            "arm_region_name": arm_region_name,
            "product_id": product_id,
            "sku_id": sku_id,
            "api_type": api_type,
            "reservation_term": reservation_term,
            "unit_of_measure": unit_of_measure,
            "effective_start_date": effective_start_date.isoformat(
                timespec="microseconds"
            ),
            "tier_minimum_units": str(tier_minimum_units),
            "is_primary_meter_region": is_primary_meter_region,
        }

        canonical_key = json.dumps(
            key_payload,
            ensure_ascii=False,
            sort_keys=True,
            separators=(",", ":"),
        )

        return hashlib.sha256(canonical_key.encode("utf-8")).hexdigest()

    @staticmethod
    def _build_source_hash(
        *,
        currency_code: str,
        tier_minimum_units: Decimal,
        reservation_term: str,
        retail_price: Decimal,
        unit_price: Decimal,
        arm_region_name: str,
        location: str | None,
        effective_start_date: datetime,
        meter_id: str,
        meter_name: str,
        product_id: str,
        product_name: str | None,
        sku_id: str,
        sku_name: str | None,
        service_name: str | None,
        service_id: str | None,
        service_family: str | None,
        unit_of_measure: str,
        api_type: str,
        is_primary_meter_region: bool | None,
        arm_sku_name: str | None,
    ) -> str:
        source_payload: dict[str, object] = {
            "currency_code": currency_code,
            "tier_minimum_units": str(tier_minimum_units),
            "reservation_term": reservation_term or None,
            "retail_price": str(retail_price),
            "unit_price": str(unit_price),
            "arm_region_name": arm_region_name,
            "location": location,
            "effective_start_date": effective_start_date.isoformat(
                timespec="microseconds"
            ),
            "meter_id": meter_id,
            "meter_name": meter_name or None,
            "product_id": product_id,
            "product_name": product_name,
            "sku_id": sku_id,
            "sku_name": sku_name,
            "service_name": service_name,
            "service_id": service_id,
            "service_family": service_family,
            "unit_of_measure": unit_of_measure or None,
            "api_type": api_type,
            "is_primary_meter_region": is_primary_meter_region,
            "arm_sku_name": arm_sku_name,
        }

        canonical_payload = json.dumps(
            source_payload,
            ensure_ascii=False,
            sort_keys=True,
            separators=(",", ":"),
        )

        return hashlib.sha256(canonical_payload.encode("utf-8")).hexdigest()

    @staticmethod
    def _json_safe_source(
        record: Mapping[str, object],
    ) -> dict[str, object]:
        return {
            key: AzureRetailPriceCatalogTransformer._json_safe_value(value)
            for key, value in record.items()
            if not key.startswith("_")
        }

    @classmethod
    def _json_safe_value(cls, value: object) -> object:
        if value is None:
            return None

        if isinstance(value, (str, int, float, bool)):
            return value

        if isinstance(value, Decimal):
            return str(value)

        if isinstance(value, datetime):
            return value.isoformat()

        if isinstance(value, Mapping):
            mapping = cast(Mapping[object, object], value)
            return {
                str(key): cls._json_safe_value(item) for key, item in mapping.items()
            }

        if isinstance(value, Sequence) and not isinstance(
            value,
            (str, bytes, bytearray),
        ):
            sequence = cast(Sequence[object], value)
            return [cls._json_safe_value(item) for item in sequence]

        return str(value)

    @staticmethod
    def _require_string(value: object, field_name: str) -> str:
        normalized = AzureRetailPriceCatalogTransformer._optional_string(value)
        if normalized is None:
            raise ValueError(f"Le champ Retail {field_name!r} est obligatoire.")
        return normalized

    @staticmethod
    def _optional_string(value: object) -> str | None:
        if value is None:
            return None
        if isinstance(value, str):
            normalized = value.strip()
            return normalized or None
        if isinstance(value, (int, float, Decimal, bool)):
            return str(value)
        raise TypeError(
            f"Valeur Retail non convertible en chaîne: {type(value).__name__}."
        )

    @staticmethod
    def _require_decimal(value: object, field_name: str) -> Decimal:
        if value is None:
            raise ValueError(f"Le champ Retail {field_name!r} est obligatoire.")
        if isinstance(value, bool):
            raise TypeError(f"Le champ Retail {field_name!r} ne peut pas être booléen.")
        if isinstance(value, Decimal):
            return value
        if isinstance(value, (str, int, float)):
            return Decimal(str(value))
        raise TypeError(f"Le champ Retail {field_name!r} n'est pas numérique.")

    @staticmethod
    def _decimal_or_zero(value: object) -> Decimal:
        if value is None:
            return Decimal(0)
        return AzureRetailPriceCatalogTransformer._require_decimal(
            value, "tierMinimumUnits"
        )

    @staticmethod
    def _bool_or_none(value: object) -> bool | None:
        if value is None:
            return None
        if isinstance(value, bool):
            return value
        raise TypeError("isPrimaryMeterRegion doit être booléen ou null.")

    @staticmethod
    def _parse_datetime(value: object, field_name: str) -> datetime:
        if isinstance(value, datetime):
            parsed = value
        elif isinstance(value, str):
            raw = value.strip()
            if not raw:
                raise ValueError(f"Le champ Retail {field_name!r} est vide.")
            try:
                parsed = datetime.fromisoformat(raw)
            except ValueError as exc:
                raise ValueError(
                    f"Date Retail invalide pour {field_name!r}: {value!r}."
                ) from exc
        else:
            raise TypeError(
                f"Le champ Retail {field_name!r} doit être un datetime ou une chaîne."
            )

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

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