from __future__ import annotations

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

from sqlalchemy import MetaData, Table, create_engine, select
from sqlalchemy.engine import Engine

from finops_batches.domain.models import BatchExecutionContext, Record


class AzureSponsorshipUsageBronzeExtractor:
    """Read RAW UsageAggregates Bronze rows for one acquisition date.

    Bronze grain: one row = one object returned in UsageAggregates value[].
    """

    def __init__(
        self,
        *,
        database_url: str,
        table_name: str = "azure_sponsorship_billing_bronze",
    ) -> None:
        self._engine: Engine = create_engine(database_url, pool_pre_ping=True)
        metadata = MetaData()
        self._table = Table(table_name, metadata, autoload_with=self._engine)

        required = {
            "id",
            "business_date",
            "payload",
            "source_hash",
            "ingestion_run_id",
            "page_number",
            "source_record_number",
        }
        missing = sorted(required.difference(self._table.c.keys()))
        if missing:
            raise ValueError(
                f"Colonnes RAW Bronze absentes de {table_name!r}: " + ", ".join(missing)
            )

    def extract(self, context: BatchExecutionContext) -> list[Record]:
        t = self._table
        statement = (
            select(
                t.c.id.label("source_bronze_id"),
                t.c.business_date,
                t.c.payload,
                t.c.source_hash.label("source_payload_hash"),
                t.c.ingestion_run_id.label("source_ingestion_run_id"),
                t.c.page_number,
                t.c.source_record_number,
                t.c.api_version,
            )
            .where(t.c.business_date == context.business_date)
            .order_by(t.c.page_number, t.c.source_record_number, t.c.id)
        )

        with self._engine.connect() as connection:
            return [
                cast(Record, dict(row))
                for row in connection.execute(statement).mappings()
            ]

    def close(self) -> None:
        self._engine.dispose()


class AzureSponsorshipUsageSilverTransformer:
    """Normalize one RAW UsageAggregates object into one provider Silver row."""

    NORMALIZATION_VERSION = "azure-usage-v2"

    def transform(self, records: Sequence[Record]) -> list[Record]:
        normalized_at = self._to_database_datetime(datetime.now(UTC))
        return [
            self._normalize_usage(
                self._decode_payload(bronze.get("payload")),
                bronze=bronze,
                normalized_at=normalized_at,
            )
            for bronze in records
        ]

    @classmethod
    def _normalize_usage(
        cls,
        item: Mapping[str, object],
        *,
        bronze: Mapping[str, object],
        normalized_at: datetime,
    ) -> Record:
        properties = cls._required_mapping(item.get("properties"), "properties")

        instance_data = cls._parse_json_mapping(
            properties.get("instanceData"),
            field_name="instanceData",
        )

        microsoft_resources = cls._as_optional_mapping(
            instance_data.get("Microsoft.Resources"),
            "instanceData.Microsoft.Resources",
        )
        resource_context = microsoft_resources or instance_data

        resource_id = cls._as_string(
            cls._first_value(properties, "resourceId", "instanceId")
        )
        if resource_id is None:
            resource_id = cls._as_string(resource_context.get("resourceUri"))

        resource_group = cls._as_string(
            cls._first_value(properties, "resourceGroup", "resourceGroupName")
        )
        if resource_group is None and resource_id is not None:
            resource_group = cls._resource_group_from_id(resource_id)

        resource_name = cls._as_string(
            cls._first_value(properties, "resourceName", "instanceName")
        )
        if resource_name is None and resource_id is not None:
            resource_name = cls._resource_name_from_id(resource_id)

        meter_info = cls._as_optional_mapping(
            resource_context.get("meterInfo"),
            "instanceData.Microsoft.Resources.meterInfo",
        )
        resource_tags = cls._as_optional_mapping(
            resource_context.get("tags"),
            "instanceData.Microsoft.Resources.tags",
        )
        additional_info = cls._as_optional_mapping(
            resource_context.get("additionalInfo"),
            "instanceData.Microsoft.Resources.additionalInfo",
        )
        info_fields = cls._as_optional_mapping(
            properties.get("infoFields"),
            "properties.infoFields",
        )

        return cast(
            Record,
            {
                "business_date": bronze.get("business_date"),
                "source_id": cls._as_string(item.get("id")),
                "source_name": cls._as_string(item.get("name")),
                "source_type": cls._as_string(item.get("type")),
                "subscription_id": cls._as_string(properties.get("subscriptionId")),
                "subscription_name": cls._as_string(properties.get("subscriptionName")),
                "usage_start": cls._as_datetime(
                    cls._first_value(properties, "usageStartTime", "usageStart")
                ),
                "usage_end": cls._as_datetime(
                    cls._first_value(properties, "usageEndTime", "usageEnd")
                ),
                "meter_id": cls._as_string(properties.get("meterId")),
                "meter_name": cls._as_string(properties.get("meterName")),
                "meter_region": cls._as_string(properties.get("meterRegion")),
                "meter_category": cls._as_string(properties.get("meterCategory")),
                "meter_sub_category": cls._as_string(
                    properties.get("meterSubCategory")
                ),
                "unit": cls._as_string(properties.get("unit")),
                "quantity": cls._as_decimal(properties.get("quantity")),
                "resource_group": resource_group,
                "resource_id": resource_id,
                "resource_name": resource_name,
                "resource_location": cls._as_string(resource_context.get("location")),
                "resource_tags": cls._serialize_optional(resource_tags),
                "meter_info": cls._serialize_optional(meter_info),
                "meter_offering_id": cls._as_string(
                    meter_info.get("OfferingId") if meter_info is not None else None
                ),
                "meter_location_id": cls._as_string(
                    meter_info.get("LocationId") if meter_info is not None else None
                ),
                "additional_info": cls._serialize_optional(additional_info),
                "info_fields": cls._serialize_optional(info_fields),
                "instance_data": cls._serialize_optional(instance_data),
                "source_bronze_id": bronze.get("source_bronze_id"),
                "source_record_number": bronze.get("source_record_number"),
                "source_payload_hash": bronze.get("source_payload_hash"),
                "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 _decode_payload(value: object) -> dict[str, object]:
        if not isinstance(value, str):
            raise TypeError("Le payload Bronze doit être une chaîne JSON.")

        try:
            decoded: object = json.loads(value)
        except json.JSONDecodeError as exc:
            raise ValueError("Le payload Bronze n'est pas un JSON valide.") from exc

        if not isinstance(decoded, dict):
            raise TypeError("Le payload Bronze 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("Les clés du payload Bronze doivent être des chaînes.")
            result[key] = item_value

        return result

    @staticmethod
    def _first_value(values: Mapping[str, object], *keys: str) -> object:
        for key in keys:
            value = values.get(key)
            if value is not None:
                return value
        return None

    @staticmethod
    def _required_mapping(value: object, field_name: str) -> dict[str, object]:
        if value is None:
            raise KeyError(f"Le champ Azure {field_name!r} est absent.")
        return AzureSponsorshipUsageSilverTransformer._mapping(value, field_name)

    @staticmethod
    def _mapping(value: object, field_name: str) -> dict[str, object]:
        if not isinstance(value, dict):
            raise TypeError(f"Le champ Azure {field_name!r} doit être un objet JSON.")

        raw_mapping = cast(dict[object, object], value)
        result: dict[str, object] = {}

        for key, item_value in raw_mapping.items():
            if not isinstance(key, str):
                raise TypeError(
                    f"Les clés du champ Azure {field_name!r} doivent être des chaînes."
                )
            result[key] = item_value

        return result

    @classmethod
    def _as_optional_mapping(
        cls,
        value: object,
        field_name: str,
    ) -> dict[str, object] | None:
        if value is None:
            return None
        return cls._mapping(value, field_name)

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

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

            return cls._mapping(
                raw_mapping,
                field_name,
            )

        if not isinstance(value, str):
            raise TypeError(
                f"Le champ Azure {field_name!r} "
                "doit être une chaîne JSON "
                "ou un objet JSON."
            )

        normalized = value.strip()

        if not normalized:
            return {}

        try:
            decoded: object = json.loads(normalized)
        except json.JSONDecodeError as exc:
            raise ValueError(
                f"Le champ Azure {field_name!r} n'est pas un JSON valide."
            ) from exc

        return cls._mapping(
            decoded,
            field_name,
        )

    @staticmethod
    def _as_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 Azure non convertible en chaîne: {type(value).__name__}."
        )

    @staticmethod
    def _as_decimal(value: object) -> Decimal | None:
        if value is None:
            return None
        if isinstance(value, bool):
            raise TypeError("Une quantité Azure ne peut pas être booléenne.")
        if isinstance(value, Decimal):
            return value
        if not isinstance(value, (str, int, float)):
            raise TypeError(
                f"Valeur Azure non convertible en Decimal: {type(value).__name__}."
            )

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

    @classmethod
    def _as_datetime(cls, value: object) -> datetime | None:
        if value is None:
            return None
        if isinstance(value, datetime):
            return cls._to_database_datetime(value)
        if not isinstance(value, str):
            raise TypeError(
                "La valeur de date Azure doit être une chaîne ou un datetime."
            )

        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

        return cls._to_database_datetime(parsed)

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

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

    @staticmethod
    def _resource_group_from_id(resource_id: str) -> str | None:
        match = re.search(
            r"/resourceGroups/([^/]+)",
            resource_id,
            flags=re.IGNORECASE,
        )
        return match.group(1) if match is not None else None

    @staticmethod
    def _resource_name_from_id(resource_id: str) -> str | None:
        normalized = resource_id.rstrip("/")
        if not normalized:
            return None
        return normalized.rsplit("/", maxsplit=1)[-1] or None

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