from __future__ import annotations

import os
from typing import Optional


def resolve_google_api_key(api_key: Optional[str] = None) -> str:
    """Resolve the Google Gemini API key.

    Resolution order:
    1) explicit api_key parameter
    2) environment variable GOOGLE_API_KEY (recommended)
    3) environment variable GEMINI_API_KEY (legacy alias)

    If both GOOGLE_API_KEY and GEMINI_API_KEY are set, GOOGLE_API_KEY wins.
    """
    if api_key is not None:
        key = str(api_key).strip()
        if not key:
            raise RuntimeError("api_key is empty.")
        return key

    google_key = (os.environ.get("GOOGLE_API_KEY") or "").strip()
    if google_key:
        return google_key

    gemini_key = (os.environ.get("GEMINI_API_KEY") or "").strip()
    if gemini_key:
        return gemini_key

    raise RuntimeError("Missing API key. Set GOOGLE_API_KEY (recommended) or GEMINI_API_KEY.")


__all__ = ["resolve_google_api_key"]
