#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Centralized provider availability detection.

Single source of truth for which LLM providers are reachable.
Import from here instead of scattering probe logic across modules.
"""
from __future__ import annotations

import os
import shutil

_availability_cache: dict[str, bool] | None = None
_claude_cli_cache: bool | None = None


def _probe_ollama() -> bool:
    """Quick probe to see if Ollama is reachable."""
    try:
        import urllib.request
        endpoint = os.environ.get("OLLAMA_ENDPOINT", "http://localhost:11434")
        req = urllib.request.Request(f"{endpoint}/api/tags", method="GET")
        with urllib.request.urlopen(req, timeout=3):
            return True
    except Exception:
        return False


def _has_claude_cli() -> bool:
    """Check if Claude CLI is installed (subscription-based access)."""
    global _claude_cli_cache
    if _claude_cli_cache is None:
        _claude_cli_cache = shutil.which("claude") is not None
    return _claude_cli_cache


def check_availability() -> dict[str, bool]:
    """Detect which providers have valid credentials / reachability."""
    global _availability_cache
    if _availability_cache is not None:
        return _availability_cache
    avail: dict[str, bool] = {}
    avail["anthropic"] = bool(os.environ.get("ANTHROPIC_API_KEY")) or _has_claude_cli()
    avail["google"] = bool(
        os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
    )
    avail["ollama"] = _probe_ollama()
    _availability_cache = avail
    return avail


def reset_availability():
    """Force re-check of provider availability on next call."""
    global _availability_cache, _claude_cli_cache
    _availability_cache = None
    _claude_cli_cache = None


def is_premium_available() -> bool:
    """True if Anthropic or Google (paid tier) is reachable."""
    avail = check_availability()
    return avail.get("anthropic", False) or avail.get("google", False)


def is_free_only() -> bool:
    """True if ONLY Ollama is available (no paid providers)."""
    avail = check_availability()
    return avail.get("ollama", False) and not is_premium_available()
