"""
Model caching utilities to avoid re-downloading large AI models
"""
import os
import logging
from pathlib import Path

logger = logging.getLogger(__name__)

# Base directory for the project
BASE_DIR = Path(__file__).resolve().parent.parent

# Model cache directory - stores downloaded models locally
MODEL_CACHE_DIR = BASE_DIR / "model_cache"
MODEL_CACHE_DIR.mkdir(exist_ok=True)

def get_model_cache_path():
    """
    Get the path to the model cache directory.
    This ensures models are downloaded once and reused.
    """
    return str(MODEL_CACHE_DIR)

def setup_model_cache():
    """
    Set up environment variables to use local model cache.
    This prevents re-downloading models on every startup.
    """
    # Set Hugging Face cache directory
    os.environ["TRANSFORMERS_CACHE"] = str(MODEL_CACHE_DIR / "transformers")
    os.environ["HF_HOME"] = str(MODEL_CACHE_DIR / "huggingface")
    
    # Set PyTorch hub cache (for YOLO models)
    os.environ["TORCH_HOME"] = str(MODEL_CACHE_DIR / "torch")
    
    # Ultralytics YOLO cache
    os.environ["YOLO_CONFIG_DIR"] = str(MODEL_CACHE_DIR / "ultralytics")
    
    logger.info(f"Model cache directory set to: {MODEL_CACHE_DIR}")
    return MODEL_CACHE_DIR

def check_cached_models():
    """
    Check what models are already cached locally.
    """
    cache_info = {
        "cache_dir": str(MODEL_CACHE_DIR),
        "cache_exists": MODEL_CACHE_DIR.exists(),
        "cache_size_mb": 0,
        "cached_models": []
    }
    
    if MODEL_CACHE_DIR.exists():
        # Calculate cache size
        total_size = sum(
            f.stat().st_size for f in MODEL_CACHE_DIR.rglob('*') if f.is_file()
        )
        cache_info["cache_size_mb"] = round(total_size / (1024 * 1024), 2)
        
        # List cached model directories
        for subdir in MODEL_CACHE_DIR.iterdir():
            if subdir.is_dir():
                cache_info["cached_models"].append(subdir.name)
    
    return cache_info