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 AzureSponsorshipBillingTransformer:
    def transform(
        self,
        records: Sequence[Record],
    ) -> list[Record]:
        ingestion_time = datetime.now(UTC).replace(tzinfo=None)

        return [
            self._transform_record(
                record,
                ingestion_time=ingestion_time,
            )
            for record in records
        ]

    @classmethod
    def _transform_record(
        cls,
        record: Record,
        *,
        ingestion_time: datetime,
    ) -> Record:
        root = cls._mapping(
            record,
            field_name="record",
            allow_none=False,
        )

        properties = cls._mapping(
            root.get("properties"),
            field_name="properties",
            allow_none=True,
        )

        instance_data = cls._instance_data(properties.get("instanceData"))

        microsoft_resources = cls._nested_mapping(
            instance_data,
            key="Microsoft.Resources",
            field_name="instanceData.Microsoft.Resources",
        )

        explicit_resource_id = cls._string(
            cls._first_present(
                properties,
                "resourceId",
                "instanceId",
            )
        )

        instance_resource_id = cls._string(
            cls._first_present(
                microsoft_resources,
                "resourceUri",
                "resourceId",
            )
        )

        if instance_resource_id is None:
            instance_resource_id = cls._string(
                cls._first_present(
                    instance_data,
                    "resourceUri",
                    "resourceId",
                )
            )

        resource_id = explicit_resource_id or instance_resource_id

        explicit_resource_group = cls._string(
            cls._first_present(
                properties,
                "resourceGroup",
                "resourceGroupName",
            )
        )

        resource_group = explicit_resource_group or cls._resource_group_from_id(
            resource_id
        )

        explicit_resource_name = cls._string(
            cls._first_present(
                properties,
                "resourceName",
                "instanceName",
            )
        )

        resource_name = explicit_resource_name or cls._resource_name_from_id(
            resource_id
        )

        resource_location = cls._string(
            cls._first_present(
                microsoft_resources,
                "location",
            )
        )

        if resource_location is None:
            resource_location = cls._string(
                cls._first_present(
                    instance_data,
                    "location",
                )
            )

        meter_info_mapping = cls._nested_mapping(
            microsoft_resources,
            key="meterInfo",
            field_name=("instanceData.Microsoft.Resources.meterInfo"),
        )

        if not meter_info_mapping:
            meter_info_mapping = cls._mapping_if_present(
                properties.get("meterInfo"),
                field_name="meterInfo",
            )

        additional_info_mapping = cls._nested_mapping(
            microsoft_resources,
            key="additionalInfo",
            field_name=("instanceData.Microsoft.Resources.additionalInfo"),
        )

        if not additional_info_mapping:
            additional_info_mapping = cls._mapping_if_present(
                properties.get("additionalInfo"),
                field_name="additionalInfo",
            )

        resource_tags_mapping = cls._nested_mapping(
            microsoft_resources,
            key="tags",
            field_name=("instanceData.Microsoft.Resources.tags"),
        )

        if not resource_tags_mapping:
            resource_tags_mapping = cls._nested_mapping(
                instance_data,
                key="tags",
                field_name="instanceData.tags",
            )

        info_fields_mapping = cls._mapping_if_present(
            properties.get("infoFields"),
            field_name="infoFields",
        )

        meter_offering_id = cls._string(
            cls._first_present(
                meter_info_mapping,
                "OfferingId",
                "offeringId",
                "MeterOfferingId",
                "meterOfferingId",
            )
        )

        meter_location_id = cls._string(
            cls._first_present(
                meter_info_mapping,
                "LocationId",
                "locationId",
                "MeterLocationId",
                "meterLocationId",
            )
        )

        usage_start = cls._datetime(
            cls._first_present(
                properties,
                "usageStartTime",
                "usageStart",
            )
        )

        usage_end = cls._datetime(
            cls._first_present(
                properties,
                "usageEndTime",
                "usageEnd",
            )
        )

        result: Record = {
            "source_id": cls._string(root.get("id")),
            "source_name": cls._string(root.get("name")),
            "source_type": cls._string(root.get("type")),
            "subscription_id": cls._string(properties.get("subscriptionId")),
            "subscription_name": cls._string(properties.get("subscriptionName")),
            "usage_start": usage_start,
            "usage_end": usage_end,
            "meter_id": cls._string(properties.get("meterId")),
            "meter_name": cls._string(properties.get("meterName")),
            "meter_region": cls._string(properties.get("meterRegion")),
            "meter_category": cls._string(properties.get("meterCategory")),
            "meter_sub_category": cls._string(properties.get("meterSubCategory")),
            "unit": cls._string(properties.get("unit")),
            "quantity": cls._decimal(properties.get("quantity")),
            "resource_group": resource_group,
            "resource_id": resource_id,
            "resource_name": resource_name,
            "resource_location": (resource_location),
            "resource_tags": cls._json_string(resource_tags_mapping),
            "meter_info": cls._json_string(meter_info_mapping),
            "meter_offering_id": (meter_offering_id),
            "meter_location_id": (meter_location_id),
            "additional_info": cls._json_string(additional_info_mapping),
            "info_fields": cls._json_string(info_fields_mapping),
            "instance_data": cls._json_string(instance_data),
            "raw_payload": json.dumps(
                root,
                ensure_ascii=False,
                separators=(",", ":"),
                default=str,
            ),
            "ingestion_run_id": None,
            "ingestion_time": ingestion_time,
        }

        return result

    @classmethod
    def _instance_data(
        cls,
        value: object,
    ) -> dict[str, object]:
        if value is None:
            return {}

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

            if not normalized:
                return {}

            try:
                parsed: object = json.loads(normalized)
            except json.JSONDecodeError as exc:
                raise ValueError(
                    "Le champ Azure 'instanceData' doit contenir un JSON valide."
                ) from exc

            if not isinstance(
                parsed,
                Mapping,
            ):
                raise TypeError(
                    "Le champ Azure 'instanceData' doit contenir un objet JSON."
                )

            parsed_mapping = cast(
                Mapping[object, object],
                parsed,
            )

            return cls._mapping(
                parsed_mapping,
                field_name="instanceData",
                allow_none=False,
            )

        if isinstance(
            value,
            Mapping,
        ):
            raw_mapping = cast(
                Mapping[object, object],
                value,
            )

            return cls._mapping(
                raw_mapping,
                field_name="instanceData",
                allow_none=False,
            )

        raise TypeError(
            "Le champ Azure 'instanceData' doit être une chaîne JSON ou un objet JSON."
        )

    @classmethod
    def _nested_mapping(
        cls,
        source: Mapping[str, object],
        *,
        key: str,
        field_name: str,
    ) -> dict[str, object]:
        value = source.get(key)

        if value is None:
            return {}

        if not isinstance(
            value,
            Mapping,
        ):
            return {}

        raw_mapping = cast(
            Mapping[object, object],
            value,
        )

        return cls._mapping(
            raw_mapping,
            field_name=field_name,
            allow_none=False,
        )

    @classmethod
    def _mapping_if_present(
        cls,
        value: object,
        *,
        field_name: str,
    ) -> dict[str, object]:
        if value is None:
            return {}

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

            if not normalized:
                return {}

            try:
                parsed: object = json.loads(normalized)
            except json.JSONDecodeError:
                return {}

            if not isinstance(
                parsed,
                Mapping,
            ):
                return {}

            raw_mapping = cast(
                Mapping[object, object],
                parsed,
            )

            return cls._mapping(
                raw_mapping,
                field_name=field_name,
                allow_none=False,
            )

        if not isinstance(
            value,
            Mapping,
        ):
            return {}

        raw_mapping = cast(
            Mapping[object, object],
            value,
        )

        return cls._mapping(
            raw_mapping,
            field_name=field_name,
            allow_none=False,
        )

    @staticmethod
    def _mapping(
        value: object,
        *,
        field_name: str,
        allow_none: bool,
    ) -> dict[str, object]:
        if value is None:
            if allow_none:
                return {}

            raise TypeError(f"Le champ Azure '{field_name}' doit être un objet JSON.")

        if not isinstance(
            value,
            Mapping,
        ):
            raise TypeError(f"Le champ Azure '{field_name}' doit être un objet JSON.")

        raw_mapping = cast(
            Mapping[object, object],
            value,
        )

        result: dict[str, object] = {}

        for key, item in raw_mapping.items():
            if not isinstance(
                key,
                str,
            ):
                raise TypeError(
                    f"Les clés du champ Azure '{field_name}' doivent être des chaînes."
                )

            result[key] = item

        return result

    @staticmethod
    def _first_present(
        source: Mapping[str, object],
        *keys: str,
    ) -> object:
        for key in keys:
            if key in source:
                return source[key]

        return None

    @staticmethod
    def _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("La valeur Azure ne peut pas être convertie en chaîne.")

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

        if isinstance(
            value,
            bool,
        ):
            raise TypeError(
                "Une valeur booléenne ne peut pas être convertie en nombre décimal."
            )

        if isinstance(
            value,
            Decimal,
        ):
            return value

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

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

        if not isinstance(
            value,
            str,
        ):
            raise TypeError(
                "La valeur Azure ne peut pas être convertie en nombre décimal."
            )

        normalized = value.strip().replace(",", ".")

        if not normalized:
            return None

        try:
            return Decimal(normalized)
        except InvalidOperation as exc:
            raise ValueError(f"Valeur numérique Azure invalide : {value!r}.") from exc

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

        if isinstance(
            value,
            datetime,
        ):
            parsed = value
        elif isinstance(
            value,
            str,
        ):
            normalized = value.strip()

            if not normalized:
                return None

            try:
                parsed = datetime.fromisoformat(normalized)
            except ValueError as exc:
                raise ValueError(f"Date Azure invalide : {value!r}.") from exc
        else:
            raise TypeError("La date Azure doit être une chaîne ou un datetime.")

        if parsed.tzinfo is None:
            return parsed

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

    @staticmethod
    def _resource_group_from_id(
        resource_id: str | None,
    ) -> str | None:
        if resource_id is None:
            return None

        parts = [part for part in (resource_id.split("/")) if part]

        for index, part in enumerate(parts):
            if part.casefold() == "resourcegroups" and index + 1 < len(parts):
                return parts[index + 1]

        return None

    @staticmethod
    def _resource_name_from_id(
        resource_id: str | None,
    ) -> str | None:
        if resource_id is None:
            return None

        parts = [part for part in (resource_id.split("/")) if part]

        if not parts:
            return None

        return parts[-1]

    @staticmethod
    def _json_string(
        value: Mapping[str, object],
    ) -> str | None:
        if not value:
            return None

        return json.dumps(
            dict(value),
            ensure_ascii=False,
            separators=(",", ":"),
            default=str,
        )
