"""AWS Pricing API client for supplemental cost estimates.

Contract:
- get_aws_supplemental_costs() returns list[CostLineItem] with source="pricing_api".
- API failure -> empty list (no exception).
- Uses boto3 Pricing client (us-east-1 only).
"""

from __future__ import annotations

import json
import sys

from complyform.core.cloud_intelligence.cost_estimator import CostLineItem

__all__ = ["get_aws_supplemental_costs"]

# AWS region name to location mapping (for Pricing API)
_REGION_LOCATION_MAP: dict[str, str] = {
    "us-east-1": "US East (N. Virginia)",
    "us-east-2": "US East (Ohio)",
    "us-west-1": "US West (N. California)",
    "us-west-2": "US West (Oregon)",
    "eu-west-1": "EU (Ireland)",
    "eu-central-1": "EU (Frankfurt)",
    "ap-southeast-1": "Asia Pacific (Singapore)",
    "ap-northeast-1": "Asia Pacific (Tokyo)",
}


def get_aws_supplemental_costs(region: str = "us-east-1") -> list[CostLineItem]:
    """Fetch supplemental AWS costs from Pricing API.

    Covers: KMS key management, CloudWatch Logs, VPC endpoints.
    """
    items: list[CostLineItem] = []
    try:
        import boto3  # type: ignore
    except ImportError:
        print("Warning: boto3 not installed, skipping AWS pricing", file=sys.stderr)
        return items

    location = _REGION_LOCATION_MAP.get(region, "US East (N. Virginia)")

    try:
        client = boto3.client("pricing", region_name="us-east-1")

        # KMS pricing
        kms_price = _get_product_price(
            client,
            "awskms",
            [
                {"Type": "TERM_MATCH", "Field": "location", "Value": location},
                {"Type": "TERM_MATCH", "Field": "group", "Value": "KMS-Keys"},
            ],
        )
        if kms_price is not None:
            items.append(
                CostLineItem(
                    category="encryption",
                    description="AWS KMS customer managed key (per month)",
                    monthly_cost=kms_price,
                    resource_count=1,
                    source="pricing_api",
                    controls=["CIS-AWS-3.8", "A.8.24"],
                )
            )

        # CloudWatch Logs pricing
        log_price = _get_product_price(
            client,
            "AmazonCloudWatch",
            [
                {"Type": "TERM_MATCH", "Field": "location", "Value": location},
                {"Type": "TERM_MATCH", "Field": "group", "Value": "Ingestion"},
            ],
        )
        if log_price is not None:
            items.append(
                CostLineItem(
                    category="logging",
                    description="CloudWatch Logs ingestion (per GB)",
                    monthly_cost=log_price,
                    resource_count=1,
                    source="pricing_api",
                    controls=["CIS-AWS-3.1", "A.8.15"],
                )
            )
    except Exception as exc:
        print(f"Warning: AWS pricing API error: {exc}", file=sys.stderr)

    return items


def _get_product_price(
    client: object,
    service_code: str,
    filters: list[dict[str, str]],
) -> float | None:
    """Fetch a single product price from the AWS Pricing API."""
    try:
        response = client.get_products(  # type: ignore[attr-defined]
            ServiceCode=service_code,
            Filters=filters,
            MaxResults=1,
        )
        price_list = response.get("PriceList", [])
        if not price_list:
            return None
        data = json.loads(price_list[0])
        terms = data.get("terms", {}).get("OnDemand", {})
        for term in terms.values():
            for dimension in term.get("priceDimensions", {}).values():
                price_str = dimension.get("pricePerUnit", {}).get("USD", "0")
                return float(price_str)
    except Exception:
        pass
    return None
