"""Registry checking utilities."""

import logging
import threading
from typing import Dict
from urllib.parse import quote

import requests

from .config import REGISTRIES

logger = logging.getLogger(__name__)

# Thread-safe cache for registry checks
_registry_cache: Dict[str, bool] = {}
_cache_lock = threading.Lock()


def check_package_exists(package_name: str, ecosystem: str) -> bool:
    """Check if a package exists in public registry."""
    cache_key = f"{ecosystem}:{package_name.lower()}"

    with _cache_lock:
        if cache_key in _registry_cache:
            return _registry_cache[cache_key]

    registry_url = REGISTRIES.get(ecosystem)
    if not registry_url:
        logger.warning(f"Unknown ecosystem: {ecosystem}")
        return False

    url = registry_url.format(package=quote(package_name))

    try:
        response = requests.get(url, timeout=10)
        exists = response.status_code == 200
        with _cache_lock:
            _registry_cache[cache_key] = exists
        logger.debug(f"Package {package_name} in {ecosystem}: {'exists' if exists else 'not found'}")
        return exists
    except requests.RequestException as e:
        logger.warning(f"Error checking {package_name} in {ecosystem}: {e}")
        with _cache_lock:
            _registry_cache[cache_key] = True  # Assume exists on error to avoid false positives
        return True
