"""Azure Retail Prices REST API client for supplemental cost estimates.

Contract:
- get_azure_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_azure_supplemental_costs"]


def get_azure_supplemental_costs(
    region: str = "eastus",
) -> list[CostLineItem]:
    """Fetch supplemental Azure costs from Retail Prices API.

    Covers: Key Vault keys, Log Analytics ingestion.
    """
    items: list[CostLineItem] = []
    try:
        import httpx  # noqa: F401
    except ImportError:
        print(
            "Warning: httpx not installed, skipping Azure pricing",
            file=sys.stderr,
        )
        return items

    try:
        # Key Vault pricing
        kv_price = _fetch_retail_price("Key Vault", region, "Standard operations")
        if kv_price is not None:
            items.append(
                CostLineItem(
                    category="encryption",
                    description="Azure Key Vault HSM key (per month)",
                    monthly_cost=kv_price,
                    resource_count=1,
                    source="pricing_api",
                    controls=["CIS-Azure-8.1", "A.8.24"],
                )
            )

        # Log Analytics pricing
        la_price = _fetch_retail_price("Log Analytics", region, "Data Ingestion")
        if la_price is not None:
            items.append(
                CostLineItem(
                    category="logging",
                    description="Log Analytics ingestion (per GB/month)",
                    monthly_cost=la_price,
                    resource_count=1,
                    source="pricing_api",
                    controls=["CIS-Azure-5.1", "A.8.15"],
                )
            )
    except Exception as exc:
        print(f"Warning: Azure pricing API error: {exc}", file=sys.stderr)

    return items


def _fetch_retail_price(
    service_name: str,
    region: str,
    meter_name_filter: str,
) -> float | None:
    """Fetch a single price from the Azure Retail Prices API."""
    import httpx

    url = "https://prices.azure.com/api/retail/prices"
    params = {
        "$filter": (f"serviceName eq '{service_name}' and armRegionName eq '{region}'"),
    }
    try:
        resp = httpx.get(url, params=params, timeout=10.0)
        resp.raise_for_status()
        data = resp.json()
    except Exception:
        return None

    for item in data.get("Items", []):
        meter_name = item.get("meterName", "")
        if meter_name_filter.lower() in meter_name.lower():
            return float(item.get("retailPrice", 0))
    return None
