"""Helper functions for indexes namespace."""

from __future__ import annotations

from typing import Any, cast


def _normalize_spec(self: Any, spec: dict[str, Any]) -> dict[str, object]:
    """Normalize spec to API format.

    Handles both simple serverless specs and full spec objects.

    Args:
        spec: Index specification dict

    Returns:
        Normalized spec dict for API request
    """
    # If spec has "cloud" key directly, it's a simple serverless spec
    if "cloud" in spec:
        if "region" not in spec:
            raise ValueError(
                "Serverless spec requires both 'cloud' and 'region' keys. "
                f"Got spec with 'cloud': {spec['cloud']!r} but missing 'region'."
            )
        serverless_spec: dict[str, object] = {
            "cloud": spec["cloud"],
            "region": spec["region"],
        }

        # Add read_capacity if specified
        if "read_capacity" in spec:
            serverless_spec["read_capacity"] = spec["read_capacity"]

        return {"serverless": serverless_spec}

    # If spec has "environment" key, determine if it's a pod or BYOC spec
    if "environment" in spec:
        # Check if it's a pod spec or BYOC spec
        if "pod_type" in spec:
            # It's a pod spec
            return {"pod": spec}

        # Check for pod-specific fields that would indicate incomplete pod spec
        pod_fields = {
            "pods",
            "replicas",
            "shards",
            "pod_size",
            "metadata_config",
            "source_collection",
        }
        has_pod_fields = any(field in spec for field in pod_fields)

        if has_pod_fields:
            # Has pod-specific fields but missing pod_type - incomplete pod spec
            raise ValueError(
                "Incomplete pod spec detected. Spec has 'environment' and pod-specific "
                "fields (pods/replicas/shards/pod_size/metadata_config/source_collection) "
                "but is missing required 'pod_type'. "
                f"Got spec: {spec}"
            )

        # It's a BYOC spec (environment without pod_type or pod-specific fields)
        byoc_spec: dict[str, object] = {
            "environment": spec["environment"],
        }
        if "read_capacity" in spec:
            byoc_spec["read_capacity"] = spec["read_capacity"]
        return {"byoc": byoc_spec}

    # Otherwise assume it's already in the correct nested format
    return cast("dict[str, object]", spec)
