"""Registry checking utilities."""

import logging
from typing import Dict, Optional
from urllib.parse import quote

import requests

from .config import REGISTRIES

logger = logging.getLogger(__name__)

# Cache for registry checks
_registry_cache: Dict[str, bool] = {}


def check_package_exists(package_name: str, ecosystem: str) -> bool:
    """Check if a package exists in public registry."""
    cache_key = f"{ecosystem}:{package_name}"
    
    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
        _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}")
        _registry_cache[cache_key] = True  # Assume exists on error to avoid false positives
        return True
