from __future__ import annotations

import json
from collections.abc import Mapping
from datetime import UTC, date, datetime
from decimal import Decimal, InvalidOperation
from typing import ClassVar, cast


class GcpFocusTransformationError(ValueError):
    """Raised when a GCP billing row cannot be converted to FOCUS."""


class GcpFocusTransformer:
    """Convert one GCP Detailed Cloud Billing row to FOCUS 1.4."""

    FOCUS_VERSION = "1.4"
    PROVIDER_NAME = "Google Cloud"
    NORMALIZATION_VERSION = "gcp-focus-v3"

    _NATIVE_GOOGLE_SELLERS: ClassVar[frozenset[str]] = frozenset(
        {"google", "google cloud"}
    )

    _SERVICE_CATEGORY_BY_NAME: ClassVar[dict[str, str]] = {
        "Artifact Registry": "Developer Tools",
        "BigQuery": "Analytics",
        "BigQuery Storage API": "Analytics",
        "Cloud Build": "Developer Tools",
        "Cloud Composer": "Integration",
        "Cloud Dataflow": "Analytics",
        "Cloud DNS": "Networking",
        "Cloud Functions": "Compute",
        "Cloud Logging": "Management and Governance",
        "Cloud Monitoring": "Management and Governance",
        "Cloud Pub/Sub": "Integration",
        "Cloud Run": "Compute",
        "Cloud Scheduler": "Integration",
        "Cloud Storage": "Storage",
        "Compute Engine": "Compute",
        "Google Kubernetes Engine": "Compute",
        "Kubernetes Engine": "Compute",
        "Networking": "Networking",
        "Secret Manager": "Security",
        "Vertex AI": "AI and Machine Learning",
        "Invoice": "Other",
    }

    def transform(
        self,
        payload: Mapping[str, object],
        *,
        business_date: date,
        ingestion_run_id: str,
        generated_at: datetime | None = None,
        billing_account_name: str | None = None,
        billing_account_name_source: str | None = None,
        invoice_issuer_name: str | None = None,
        invoice_issuer_source: str | None = None,
    ) -> dict[str, object]:
        generated_at_utc = self._utc_datetime(
            generated_at if generated_at is not None else datetime.now(UTC),
            "generated_at",
        )

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

        billing_account_id = self._required_string(
            payload.get("billing_account_id"),
            "billing_account_id",
        )
        resolved_billing_account_name = self._optional_string(billing_account_name)
        resolved_billing_account_name_source = self._reference_source(
            value=resolved_billing_account_name,
            source=billing_account_name_source,
        )
        resolved_invoice_issuer_name = self._optional_string(invoice_issuer_name)
        resolved_invoice_issuer_source = self._reference_source(
            value=resolved_invoice_issuer_name,
            source=invoice_issuer_source,
        )

        currency = self._required_currency(payload.get("currency"))
        cost = self._required_decimal(payload.get("cost"), "cost")

        invoice_month = self._required_string(invoice.get("month"), "invoice.month")
        billing_period_start, billing_period_end = self._billing_period(invoice_month)

        usage_start = self._optional_datetime(payload.get("usage_start_time"))
        usage_end = self._optional_datetime(payload.get("usage_end_time"))
        charge_period_start = usage_start or billing_period_start
        charge_period_end = usage_end or billing_period_end

        export_time = self._optional_datetime(payload.get("export_time"))

        cost_type = self._optional_string(payload.get("cost_type"))
        charge_category = self._charge_category(cost_type)
        adjustment_info = self._mapping(
            payload.get("adjustment_info"),
            "adjustment_info",
        )
        charge_class = "Correction" if adjustment_info else None

        sku_description = self._optional_string(sku.get("description"))
        service_name = self._service_name(
            service_description=self._optional_string(service.get("description")),
            charge_category=charge_category,
        )
        service_category, service_category_source = self._service_category(service_name)

        charge_description = self._charge_description(
            sku_description=sku_description,
            charge_category=charge_category,
            cost_type=cost_type,
            service_name=service_name,
        )

        seller_name = self._optional_string(payload.get("seller_name"))
        service_provider_name = self._service_provider_name(seller_name)
        host_provider_name = self._host_provider_name(
            service_provider_name=service_provider_name,
            charge_category=charge_category,
        )

        credits = self._list_of_mappings(payload.get("credits"), "credits")
        credits_total = sum(
            (self._decimal(credit.get("amount")) or Decimal(0) for credit in credits),
            Decimal(0),
        )
        billed_cost = cost + credits_total

        cost_at_list = self._decimal(payload.get("cost_at_list"))
        list_cost = cost_at_list if cost_at_list is not None else cost
        list_cost_source = (
            "GCP_COST_AT_LIST" if cost_at_list is not None else "GCP_COST_FALLBACK"
        )

        consumed_quantity = self._decimal(usage.get("amount")) or Decimal(0)
        consumed_unit = self._optional_string(usage.get("unit")) or "N/A"
        pricing_quantity = (
            self._decimal(usage.get("amount_in_pricing_units")) or consumed_quantity
        )
        pricing_unit = self._optional_string(usage.get("pricing_unit")) or consumed_unit

        applied_subscription_instance_id = self._optional_string(
            consumption_model.get("applied_subscription_instance_id")
        )
        pricing_category = (
            "Committed" if applied_subscription_instance_id is not None else "Standard"
        )

        conformance_gaps: list[str] = []
        if resolved_billing_account_name is None:
            conformance_gaps.append("BillingAccountName")
        if resolved_invoice_issuer_name is None:
            conformance_gaps.append("InvoiceIssuerName")

        conformance_status = (
            "PARTIAL" if conformance_gaps else "READY_FOR_CONFORMANCE_REVIEW"
        )

        return {
            "business_date": business_date,
            # Compatibility columns retained temporarily during the FOCUS 1.4 migration.
            "ProviderName": self.PROVIDER_NAME,
            "PublisherName": service_provider_name,
            # FOCUS 1.4 participating entities.
            "ServiceProviderName": service_provider_name,
            "HostProviderName": host_provider_name,
            "InvoiceIssuerName": resolved_invoice_issuer_name,
            # Account and billing period.
            "BillingAccountId": billing_account_id,
            "BillingAccountName": resolved_billing_account_name,
            "BillingCurrency": currency,
            "BillingPeriodStart": billing_period_start,
            "BillingPeriodEnd": billing_period_end,
            # Charge.
            "ChargePeriodStart": charge_period_start,
            "ChargePeriodEnd": charge_period_end,
            "ChargeCategory": charge_category,
            "ChargeClass": charge_class,
            "ChargeDescription": charge_description,
            # Service / SKU.
            "ServiceName": service_name,
            "ServiceCategory": service_category,
            "SkuId": self._optional_string(sku.get("id")),
            # Google Detailed Billing does not expose a stable FOCUS SKU price ID.
            "SkuPriceId": None,
            # Resource / account / location.
            "ResourceId": self._optional_string(resource.get("global_name")),
            "ResourceName": self._optional_string(resource.get("name")),
            "SubAccountId": self._optional_string(project.get("id")),
            "SubAccountName": self._optional_string(project.get("name")),
            "RegionId": self._optional_string(location.get("region")),
            "RegionName": self._optional_string(location.get("region")),
            "AvailabilityZone": self._optional_string(location.get("zone")),
            # Quantities / pricing.
            "ConsumedQuantity": consumed_quantity,
            "ConsumedUnit": consumed_unit,
            "PricingQuantity": pricing_quantity,
            "PricingUnit": pricing_unit,
            "ListUnitPrice": self._decimal(price.get("list_price")),
            "ContractedUnitPrice": self._decimal(price.get("effective_price")),
            "ListCost": list_cost,
            "ContractedCost": cost,
            "BilledCost": billed_cost,
            "EffectiveCost": billed_cost,
            "PricingCategory": pricing_category,
            # Google-specific traceability.
            "x_ServiceId": self._optional_string(service.get("id")),
            "x_CostType": cost_type,
            "x_CurrencyConversionRate": self._decimal(
                payload.get("currency_conversion_rate")
            ),
            "x_ExportTime": export_time,
            "x_Credits": self._serialize(payload.get("credits")),
            "x_Labels": self._serialize(payload.get("labels")),
            "x_SystemLabels": self._serialize(payload.get("system_labels")),
            "x_Tags": self._serialize(payload.get("tags")),
            "x_Project": self._serialize(payload.get("project")),
            "x_ConsumptionModelId": self._optional_string(consumption_model.get("id")),
            "x_ConsumptionModelDescription": self._optional_string(
                consumption_model.get("description")
            ),
            "x_AppliedSubscriptionInstanceId": applied_subscription_instance_id,
            "x_SubscriptionInstanceId": self._optional_string(
                subscription.get("instance_id")
            ),
            "x_IngestionRunId": ingestion_run_id,
            "x_GeneratedAt": generated_at_utc,
            "x_FocusVersion": self.FOCUS_VERSION,
            "x_ListCostSource": list_cost_source,
            "x_InvoicePublisherType": self._optional_string(
                invoice.get("publisher_type")
            ),
            "x_SellerName": seller_name,
            "x_ServiceCategorySource": service_category_source,
            "x_BillingAccountNameSource": resolved_billing_account_name_source,
            "x_InvoiceIssuerSource": resolved_invoice_issuer_source,
            "x_FocusConformanceStatus": conformance_status,
            "x_FocusConformanceGaps": self._serialize(conformance_gaps),
        }

    @classmethod
    def _service_provider_name(cls, seller_name: str | None) -> str:
        if seller_name is None:
            return cls.PROVIDER_NAME
        if seller_name.casefold() in cls._NATIVE_GOOGLE_SELLERS:
            return cls.PROVIDER_NAME
        return seller_name

    @classmethod
    def _host_provider_name(
        cls,
        *,
        service_provider_name: str,
        charge_category: str,
    ) -> str | None:
        if charge_category in {"Tax", "Adjustment"}:
            return None
        if service_provider_name == cls.PROVIDER_NAME:
            return cls.PROVIDER_NAME
        # Marketplace / third-party workloads may be hosted outside Google Cloud.
        return None

    @classmethod
    def _service_category(cls, service_name: str) -> tuple[str, str]:
        category = cls._SERVICE_CATEGORY_BY_NAME.get(service_name)
        if category is not None:
            return category, "EXACT_SERVICE_MAPPING"
        return "Other", "FALLBACK_OTHER"

    @staticmethod
    def _service_name(
        *,
        service_description: str | None,
        charge_category: str,
    ) -> str:
        if service_description is not None:
            return service_description
        if charge_category in {"Tax", "Adjustment"}:
            return "Invoice"
        return "Other"

    @staticmethod
    def _charge_category(cost_type: str | None) -> str:
        normalized = cost_type.casefold() if cost_type is not None else ""
        if normalized == "tax":
            return "Tax"
        if normalized in {"adjustment", "rounding_error"}:
            return "Adjustment"
        return "Usage"

    @staticmethod
    def _charge_description(
        *,
        sku_description: str | None,
        charge_category: str,
        cost_type: str | None,
        service_name: str,
    ) -> str:
        if sku_description is not None:
            return sku_description
        if charge_category == "Tax":
            return "Tax"
        if charge_category == "Adjustment":
            if cost_type is not None and cost_type.casefold() == "rounding_error":
                return "Rounding Error"
            return "Billing Adjustment"
        return service_name

    @staticmethod
    def _billing_period(invoice_month: str) -> tuple[datetime, datetime]:
        if len(invoice_month) != 6 or not invoice_month.isdigit():
            raise GcpFocusTransformationError(
                f"invoice.month doit être au format YYYYMM: {invoice_month!r}."
            )

        year = int(invoice_month[:4])
        month = int(invoice_month[4:])
        if month < 1 or month > 12:
            raise GcpFocusTransformationError(
                f"invoice.month contient un mois invalide: {invoice_month!r}."
            )

        start = datetime(year, month, 1, tzinfo=UTC)
        if month == 12:
            end = datetime(year + 1, 1, 1, tzinfo=UTC)
        else:
            end = datetime(year, month + 1, 1, tzinfo=UTC)
        return start, end

    @classmethod
    def _mapping(cls, value: object, field: str) -> dict[str, object]:
        if value is None:
            return {}
        if not isinstance(value, Mapping):
            raise TypeError(f"{field} doit être un objet JSON.")

        raw = cast(Mapping[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 _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._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:
        result = cls._optional_string(value)
        if result is None:
            raise GcpFocusTransformationError(f"{field} est obligatoire.")
        return result

    @classmethod
    def _required_currency(cls, value: object) -> str:
        currency = cls._required_string(value, "currency").upper()
        if len(currency) != 3:
            raise GcpFocusTransformationError(
                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 GcpFocusTransformationError(
                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 GcpFocusTransformationError(f"{field} est obligatoire.")
        return result

    @classmethod
    def _optional_datetime(cls, value: object) -> datetime | None:
        if value is None:
            return None
        return cls._utc_datetime(value, "datetime")

    @staticmethod
    def _utc_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 GcpFocusTransformationError(
                    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.replace(tzinfo=UTC)
        return parsed.astimezone(UTC)

    @classmethod
    def _reference_source(
        cls,
        *,
        value: str | None,
        source: str | None,
    ) -> str:
        if value is None:
            return "UNAVAILABLE_IN_GCP_DETAILED_EXPORT"
        return cls._optional_string(source) or "LOCAL_REFERENCE"

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