from __future__ import annotations

import json
from collections.abc import Sequence
from datetime import UTC, date, 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 GcpBillingBronzeExtractor:
    """Read one RAW GCP billing acquisition day from local Bronze only."""

    def __init__(
        self,
        *,
        database_url: str,
        table_name: str = "gcp_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]:
        table = self._table
        statement = (
            select(
                table.c.id.label("source_bronze_id"),
                table.c.business_date,
                table.c.payload,
                table.c.source_hash.label("source_payload_hash"),
                table.c.ingestion_run_id.label("source_ingestion_run_id"),
                table.c.page_number.label("source_page_number"),
                table.c.source_record_number,
                table.c.api_version,
            )
            .where(table.c.business_date == context.business_date)
            .order_by(
                table.c.page_number,
                table.c.source_record_number,
                table.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 GcpBillingSilverTransformer:
    """Normalize GCP Detailed Cloud Billing export rows into provider Silver."""

    NORMALIZATION_VERSION = "gcp-detailed-billing-v1"

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

        invoice = cls._mapping(payload.get("invoice"), "invoice")
        service = cls._mapping(payload.get("service"), "service")
        sku = cls._mapping(payload.get("sku"), "sku")
        project = cls._mapping(payload.get("project"), "project")
        location = cls._mapping(payload.get("location"), "location")
        usage = cls._mapping(payload.get("usage"), "usage")
        price = cls._mapping(payload.get("price"), "price")
        consumption_model = cls._mapping(
            payload.get("consumption_model"),
            "consumption_model",
        )
        subscription = cls._mapping(payload.get("subscription"), "subscription")
        resource = cls._mapping(payload.get("resource"), "resource")

        usage_start = cls._optional_datetime(payload.get("usage_start_time"))
        usage_end = cls._optional_datetime(payload.get("usage_end_time"))
        export_time = cls._required_datetime(payload.get("export_time"), "export_time")

        cost = cls._required_decimal(payload.get("cost"), "cost")
        currency = cls._required_currency(payload.get("currency"))
        credits = cls._list_of_mappings(payload.get("credits"), "credits")
        credits_total = sum(
            (cls._decimal(credit.get("amount")) or Decimal(0) for credit in credits),
            Decimal(0),
        )

        invoice_month = cls._optional_string(invoice.get("month"))
        if invoice_month is not None and (
            len(invoice_month) != 6 or not invoice_month.isdigit()
        ):
            raise ValueError(
                f"invoice.month doit être au format YYYYMM: {invoice_month!r}."
            )

        business_date = cls._required_date(
            bronze.get("business_date"),
            "business_date",
        )

        return cast(
            Record,
            {
                "business_date": business_date,
                "usage_date": usage_start.date() if usage_start is not None else None,
                "billing_account_id": cls._required_string(
                    payload.get("billing_account_id"),
                    "billing_account_id",
                ),
                "invoice_month": invoice_month,
                "invoice_publisher_type": cls._optional_string(
                    invoice.get("publisher_type")
                ),
                "cost_type": cls._optional_string(payload.get("cost_type")),
                "service_id": cls._optional_string(service.get("id")),
                "service_description": cls._optional_string(service.get("description")),
                "sku_id": cls._optional_string(sku.get("id")),
                "sku_description": cls._optional_string(sku.get("description")),
                "usage_start": usage_start,
                "usage_end": usage_end,
                "export_time": export_time,
                "project_id": cls._optional_string(project.get("id")),
                "project_number": cls._optional_string(project.get("number")),
                "project_name": cls._optional_string(project.get("name")),
                "project_ancestry_numbers": cls._optional_string(
                    project.get("ancestry_numbers")
                ),
                "project_ancestors": cls._serialize_optional(project.get("ancestors")),
                "project_labels": cls._serialize_optional(project.get("labels")),
                "labels": cls._serialize_optional(payload.get("labels")),
                "system_labels": cls._serialize_optional(payload.get("system_labels")),
                "tags": cls._serialize_optional(payload.get("tags")),
                "location": cls._optional_string(location.get("location")),
                "country": cls._optional_string(location.get("country")),
                "region": cls._optional_string(location.get("region")),
                "zone": cls._optional_string(location.get("zone")),
                "resource_name": cls._optional_string(resource.get("name")),
                "resource_global_name": cls._optional_string(
                    resource.get("global_name")
                ),
                "cost": cost,
                "cost_at_list": cls._decimal(payload.get("cost_at_list")),
                "cost_at_effective_price_default": cls._decimal(
                    payload.get("cost_at_effective_price_default")
                ),
                "cost_at_list_consumption_model": cls._decimal(
                    payload.get("cost_at_list_consumption_model")
                ),
                "credits_total": credits_total,
                "net_cost": cost + credits_total,
                "currency": currency,
                "currency_conversion_rate": cls._decimal(
                    payload.get("currency_conversion_rate")
                ),
                "usage_amount": cls._decimal(usage.get("amount")),
                "usage_unit": cls._optional_string(usage.get("unit")),
                "usage_amount_in_pricing_units": cls._decimal(
                    usage.get("amount_in_pricing_units")
                ),
                "usage_pricing_unit": cls._optional_string(usage.get("pricing_unit")),
                "credits": cls._serialize_optional(payload.get("credits")),
                "adjustment_info": cls._serialize_optional(
                    payload.get("adjustment_info")
                ),
                "transaction_type": cls._optional_string(
                    payload.get("transaction_type")
                ),
                "seller_name": cls._optional_string(payload.get("seller_name")),
                "price_list_price": cls._decimal(price.get("list_price")),
                "price_effective_price_default": cls._decimal(
                    price.get("effective_price_default")
                ),
                "price_list_price_consumption_model": cls._decimal(
                    price.get("list_price_consumption_model")
                ),
                "price_effective_price": cls._decimal(price.get("effective_price")),
                "price_tier_start_amount": cls._decimal(price.get("tier_start_amount")),
                "price_unit": cls._optional_string(price.get("unit")),
                "price_pricing_unit_quantity": cls._decimal(
                    price.get("pricing_unit_quantity")
                ),
                "consumption_model_id": cls._optional_string(
                    consumption_model.get("id")
                ),
                "consumption_model_description": cls._optional_string(
                    consumption_model.get("description")
                ),
                "subscription_instance_id": cls._optional_string(
                    subscription.get("instance_id")
                ),
                "applied_subscription_instance_id": cls._optional_string(
                    consumption_model.get("applied_subscription_instance_id")
                ),
                "source_bronze_id": cls._required_int(
                    bronze.get("source_bronze_id"),
                    "source_bronze_id",
                ),
                "source_page_number": cls._optional_int(
                    bronze.get("source_page_number")
                ),
                "source_record_number": cls._optional_int(
                    bronze.get("source_record_number")
                ),
                "source_payload_hash": cls._required_string(
                    bronze.get("source_payload_hash"),
                    "source_payload_hash",
                ),
                "source_ingestion_run_id": cls._optional_string(
                    bronze.get("source_ingestion_run_id")
                ),
                "ingestion_run_id": None,
                "normalization_version": cls.NORMALIZATION_VERSION,
                "normalized_at": normalized_at,
            },
        )

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

        try:
            decoded: object = json.loads(value)
        except json.JSONDecodeError as exc:
            raise ValueError(f"{field} n'est pas un JSON valide.") from exc

        if not isinstance(decoded, dict):
            raise TypeError(f"{field} doit contenir un objet JSON.")

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

        return GcpBillingSilverTransformer._string_key_mapping(
            decoded_mapping,
            field,
        )

    @staticmethod
    def _string_key_mapping(
        value: object,
        field: str,
    ) -> dict[str, object]:
        if not isinstance(value, dict):
            raise TypeError(f"{field} doit être un objet JSON.")

        raw = cast(dict[object, object], value)

        result: dict[str, object] = {}

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

            result[key] = item

        return result

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

    @classmethod
    def _list_of_mappings(
        cls,
        value: object,
        field: str,
    ) -> list[dict[str, object]]:
        if value is None:
            return []

        if not isinstance(value, list):
            raise TypeError(f"{field} doit être un tableau JSON.")

        raw_items = cast(list[object], value)

        return [
            cls._string_key_mapping(
                item,
                f"{field}[{index}]",
            )
            for index, item in enumerate(raw_items)
        ]

    @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)) and not isinstance(value, bool):
            return str(value)
        raise TypeError(
            f"Valeur GCP non convertible en chaîne: {type(value).__name__}."
        )

    @classmethod
    def _required_string(cls, value: object, field: str) -> str:
        normalized = cls._optional_string(value)
        if normalized is None:
            raise ValueError(f"{field} est obligatoire.")
        return normalized

    @classmethod
    def _required_currency(cls, value: object) -> str:
        currency = cls._required_string(value, "currency").upper()
        if len(currency) != 3:
            raise ValueError(f"currency doit contenir 3 caractères: {currency!r}.")
        return currency

    @staticmethod
    def _decimal(value: object) -> Decimal | None:
        if value is None:
            return None
        if isinstance(value, bool):
            raise TypeError("Une valeur numérique GCP ne peut pas être booléenne.")
        if isinstance(value, Decimal):
            return value
        if not isinstance(value, (str, int, float)):
            raise TypeError(
                f"Valeur GCP non convertible en Decimal: {type(value).__name__}."
            )
        try:
            return Decimal(str(value))
        except InvalidOperation as exc:
            raise ValueError(f"Valeur numérique GCP invalide: {value!r}.") from exc

    @classmethod
    def _required_decimal(cls, value: object, field: str) -> Decimal:
        result = cls._decimal(value)
        if result is None:
            raise ValueError(f"{field} est obligatoire.")
        return result

    @staticmethod
    def _optional_datetime(value: object) -> datetime | None:
        if value is None:
            return None
        return GcpBillingSilverTransformer._parse_datetime(value, "datetime")

    @staticmethod
    def _required_datetime(value: object, field: str) -> datetime:
        if value is None:
            raise ValueError(f"{field} est obligatoire.")
        return GcpBillingSilverTransformer._parse_datetime(value, field)

    @staticmethod
    def _parse_datetime(value: object, field: str) -> datetime:
        if isinstance(value, datetime):
            parsed = value
        elif isinstance(value, str) and value.strip():
            try:
                parsed = datetime.fromisoformat(value.strip())
            except ValueError as exc:
                raise ValueError(
                    f"{field} n'est pas un datetime ISO valide: {value!r}."
                ) from exc
        else:
            raise TypeError(f"{field} doit être un datetime ou une chaîne ISO.")

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

    @staticmethod
    def _serialize_optional(value: object) -> str | None:
        if value is None:
            return None
        return json.dumps(
            value,
            sort_keys=True,
            ensure_ascii=False,
            separators=(",", ":"),
        )

    @staticmethod
    def _required_date(value: object, field: str) -> date:
        if isinstance(value, datetime):
            return value.date()
        if isinstance(value, date):
            return value
        raise TypeError(f"{field} doit être une date.")

    @staticmethod
    def _optional_int(value: object) -> int | None:
        if value is None:
            return None
        if isinstance(value, bool) or not isinstance(value, int):
            raise TypeError("La valeur doit être un entier ou None.")
        return value

    @classmethod
    def _required_int(cls, value: object, field: str) -> int:
        result = cls._optional_int(value)
        if result is None:
            raise ValueError(f"{field} est obligatoire.")
        return result
