from __future__ import annotations

import logging
import os
from typing import Optional

from .base import BaseLLMProvider

try:  # pragma: no cover - optional dependency
    from .vertex_ai_provider import VertexAIProvider
except Exception:  # noqa: BLE001
    VertexAIProvider = None  # type: ignore

logger = logging.getLogger(__name__)

# Cache provider instance to avoid repeated init attempts
_cached_provider: Optional[BaseLLMProvider] = None
_init_attempted: bool = False


def _has_vertex_project() -> bool:
    """Check if Vertex AI project is configured."""
    return bool(
        os.getenv("VERTEX_PROJECT")
        or os.getenv("GOOGLE_CLOUD_PROJECT")
        or os.getenv("GCP_PROJECT")
    )


def get_llm_provider() -> Optional[BaseLLMProvider]:
    """Return the configured LLM provider or None if disabled.

    Defaults to Vertex AI with Gemini 3 Flash. Set LLM_PROVIDER=heuristics to disable.
    Ollama support has been removed - use Vertex AI only.
    """
    global _cached_provider, _init_attempted

    # Return cached instance if already initialized
    if _init_attempted:
        return _cached_provider

    _init_attempted = True
    provider = (os.getenv("LLM_PROVIDER") or "vertex").strip().lower()

    # Explicit disable
    if provider == "heuristics":
        return None

    # Error if Ollama is requested (no longer supported)
    if provider == "ollama":
        logger.error(
            "Ollama support has been removed. Configure Vertex AI instead: "
            "set VERTEX_PROJECT and optionally VERTEX_MODEL (default: gemini-3-flash-preview)"
        )
        return None

    # Default: Vertex AI with Gemini 3 Flash
    if VertexAIProvider is None:
        logger.error("Vertex AI SDK not available. Install google-cloud-aiplatform.")
        return None

    # Check if project is configured before attempting init
    if not _has_vertex_project():
        logger.warning("Vertex AI: VERTEX_PROJECT not set, skipping initialization")
        return None

    model = (
        os.getenv("VERTEX_MODEL")
        or os.getenv("GENAI_MODEL")
        or "gemini-3-flash-preview"
    )
    try:
        _cached_provider = VertexAIProvider(model=model)
        return _cached_provider
    except Exception as exc:  # pragma: no cover - init failure
        logger.error("Vertex AI provider failed to initialize: %s", exc)
        return None


__all__ = ["get_llm_provider"]
if VertexAIProvider is not None:  # pragma: no cover - depends on install
    __all__.append("VertexAIProvider")
