"""Shared HTTP infrastructure for Codeflash API clients."""

from __future__ import annotations

import os
from typing import Any

from .exceptions import InvalidAPIKeyError


def _resolve_url_from_env(
    env_var: str,
    prod_url: str,
    local_url: str,
) -> str:
    """Return *prod_url* or *local_url* based on an environment variable."""
    server = os.environ.get(env_var, "prod")
    if server.lower() == "local":
        return local_url
    return prod_url


def _resolve_base_url() -> str:
    """Return the AI service base URL from the environment."""
    return _resolve_url_from_env(
        "CODEFLASH_AIS_SERVER",
        "https://app.codeflash.ai",
        "http://localhost:8000",
    )


def _resolve_cfapi_base_url() -> str:
    """Return the platform API base URL from the environment."""
    return _resolve_url_from_env(
        "CODEFLASH_CFAPI_SERVER",
        "https://app.codeflash.ai",
        "http://localhost:3001",
    )


def _strip_trailing_slash(url: str) -> str:
    """Remove a trailing slash from *url*."""
    return url.rstrip("/")


def _make_session() -> Any:
    """Create a ``requests.Session`` with a deferred import."""
    import requests  # noqa: PLC0415

    return requests.Session()


def _resolve_api_key() -> str:
    """
    Read and validate *CODEFLASH_API_KEY* from the environment.
    """
    key = os.environ.get("CODEFLASH_API_KEY", "")
    if not key:
        msg = (
            "Codeflash API key not found. Set the"
            " CODEFLASH_API_KEY environment variable."
            " Generate one at"
            " https://app.codeflash.ai/app/apikeys"
        )
        raise InvalidAPIKeyError(msg)
    if not key.startswith("cf-"):
        msg = (
            "Invalid Codeflash API key — must start with"
            f" 'cf-', got '{key[:6]}…'."
            " Generate a new one at"
            " https://app.codeflash.ai/app/apikeys"
        )
        raise InvalidAPIKeyError(msg)
    return key
