"""Serverless environment detection.

Used to auto-enable session flush and generate warnings when events
might be lost due to the runtime freezing before the flush interval fires.
"""

from __future__ import annotations

import os

_SERVERLESS_ENV_VARS = (
    "AWS_LAMBDA_FUNCTION_NAME",   # AWS Lambda
    "VERCEL",                      # Vercel Functions
    "NETLIFY",                     # Netlify Functions
    "FUNCTION_TARGET",             # Google Cloud Functions
    "WEBSITE_INSTANCE_ID",         # Azure Functions
    "CF_PAGES",                    # Cloudflare Pages Functions
)

_cached: bool | None = None


def is_serverless() -> bool:
    """Detect whether the current process is running in a serverless environment.

    Checks well-known environment variables set by major serverless platforms.
    Result is cached after the first call.
    """
    global _cached  # noqa: PLW0603
    if _cached is not None:
        return _cached
    _cached = any(os.environ.get(v) for v in _SERVERLESS_ENV_VARS)
    return _cached


def _reset_serverless_cache() -> None:
    """Reset the cached result (for testing)."""
    global _cached  # noqa: PLW0603
    _cached = None
