"""GCP Cloud Billing Catalog API client for supplemental cost estimates.

Contract:
- get_gcp_supplemental_costs() returns list[CostLineItem] with source="pricing_api".
- API failure -> empty list (no exception).
- Uses public API (no auth required).
"""

from __future__ import annotations

import sys

from complyform.core.cloud_intelligence.cost_estimator import CostLineItem

__all__ = ["get_gcp_supplemental_costs"]

# GCP Cloud Billing service IDs
_KMS_SERVICE_ID = "95FF-2EF5-5EA1"
_LOGGING_SERVICE_ID = "24E6-581D-38E5"


def get_gcp_supplemental_costs(region: str = "us-east1") -> list[CostLineItem]:
    """Fetch supplemental GCP costs from Cloud Billing Catalog API.

    Covers: KMS key operations, Cloud Logging ingestion.
    """
    items: list[CostLineItem] = []
    try:
        import httpx  # noqa: F401
    except ImportError:
        print("Warning: httpx not installed, skipping GCP pricing", file=sys.stderr)
        return items

    try:
        # KMS pricing
        kms_price = _fetch_sku_price(_KMS_SERVICE_ID, "Active CMEK key versions")
        if kms_price is not None:
            items.append(
                CostLineItem(
                    category="encryption",
                    description="Cloud KMS key (per active version/month)",
                    monthly_cost=kms_price,
                    resource_count=1,
                    source="pricing_api",
                    controls=["CIS-GCP-1.10", "A.8.24"],
                )
            )

        # Logging pricing
        log_price = _fetch_sku_price(_LOGGING_SERVICE_ID, "Log Storage")
        if log_price is not None:
            items.append(
                CostLineItem(
                    category="logging",
                    description="Cloud Logging ingestion (per GB/month)",
                    monthly_cost=log_price,
                    resource_count=1,
                    source="pricing_api",
                    controls=["CIS-GCP-2.1", "A.8.15"],
                )
            )
    except Exception as exc:
        print(f"Warning: GCP pricing API error: {exc}", file=sys.stderr)

    return items


def _fetch_sku_price(service_id: str, description_filter: str) -> float | None:
    """Fetch a single SKU price from the Cloud Billing Catalog."""
    import httpx

    url = f"https://cloudbilling.googleapis.com/v1/services/{service_id}/skus"
    try:
        resp = httpx.get(url, timeout=10.0)
        resp.raise_for_status()
        data = resp.json()
    except Exception:
        return None

    for sku in data.get("skus", []):
        desc = sku.get("description", "")
        if description_filter.lower() not in desc.lower():
            continue
        pricing_info = sku.get("pricingInfo", [])
        if not pricing_info:
            continue
        expr = pricing_info[0].get("pricingExpression", {})
        rates = expr.get("tieredRates", [])
        if not rates:
            continue
        unit_price = rates[0].get("unitPrice", {})
        units = int(unit_price.get("units", "0"))
        nanos = int(unit_price.get("nanos", 0))
        return units + nanos / 1_000_000_000
    return None
