#!/usr/bin/env python3
"""
Model Cache Management Script

Use this script to:
1. Check cache status
2. Clear cache if needed
3. Estimate download requirements
"""

import sys
import shutil
from pathlib import Path

# Add the app directory to the Python path
sys.path.insert(0, str(Path(__file__).parent))

from app.model_cache import setup_model_cache, check_cached_models, MODEL_CACHE_DIR
from app.config import YOLO_MODEL, CLIP_MODEL

def show_cache_status():
    """Display detailed cache information"""
    print("=" * 60)
    print("🗂️  AI Model Cache Management")
    print("=" * 60)
    print()
    
    setup_model_cache()
    cache_info = check_cached_models()
    
    print(f"📍 Cache Location: {cache_info['cache_dir']}")
    print(f"📏 Cache Size: {cache_info['cache_size_mb']} MB")
    print(f"🗃️  Cache Exists: {cache_info['cache_exists']}")
    print(f"📂 Cached Components: {cache_info['cached_models']}")
    print()
    
    # Show model configuration
    print("🤖 Model Configuration:")
    print(f"   • YOLO: {YOLO_MODEL}")
    print(f"   • CLIP: {CLIP_MODEL}")
    print()
    
    # Show cache status
    if cache_info['cache_size_mb'] < 50:
        print("📊 Status: ⚠️  EMPTY CACHE")
        print("   • First run will download ~605MB")
        print("   • Downloads: YOLOv8n (~6MB) + CLIP (~350MB) + dependencies")
        print("   • Estimated time: 2-3 minutes (depending on internet)")
    elif cache_info['cache_size_mb'] < 400:
        print("📊 Status: ⏳ PARTIAL CACHE") 
        print("   • Some models cached, others may download")
        print("   • Remaining downloads likely < 300MB")
    else:
        print("📊 Status: ✅ FULLY CACHED")
        print("   • All models cached locally")
        print("   • No downloads needed - instant startup!")
    
    return cache_info

def clear_cache():
    """Clear the entire model cache"""
    print("\n🗑️  Clearing Model Cache...")
    
    if MODEL_CACHE_DIR.exists():
        try:
            shutil.rmtree(MODEL_CACHE_DIR)
            print(f"✅ Cache cleared: {MODEL_CACHE_DIR}")
            print("⚠️  Next startup will re-download all models (~605MB)")
        except Exception as e:
            print(f"❌ Error clearing cache: {e}")
    else:
        print("ℹ️  Cache directory doesn't exist - nothing to clear")

def main():
    """Main cache management function"""
    cache_info = show_cache_status()
    
    print("\n" + "=" * 60)
    print("🛠️  Management Options")
    print("=" * 60)
    print("1. Keep cache as-is (recommended)")
    print("2. Clear cache (forces re-download)")
    print("3. Exit")
    print()
    
    try:
        choice = input("Select option (1-3): ").strip()
        
        if choice == "1":
            print("\n✅ Cache kept intact")
            if cache_info['cache_size_mb'] < 50:
                print("💡 Tip: First AI service startup will download models")
                print("   This is normal and happens only once!")
        elif choice == "2":
            confirm = input("\n⚠️  Are you sure? This will force re-download of ~605MB (y/N): ").strip().lower()
            if confirm in ['y', 'yes']:
                clear_cache()
            else:
                print("❌ Cache clear cancelled")
        elif choice == "3":
            print("\n👋 Goodbye!")
        else:
            print("\n❌ Invalid option")
            
    except KeyboardInterrupt:
        print("\n\n👋 Goodbye!")
    except Exception as e:
        print(f"\n❌ Error: {e}")

if __name__ == "__main__":
    main()