#!/usr/bin/env python3
"""
Cleanup script for expired files using expiry database
Works with both local storage and Backblaze B2 storage backends
"""
import os
import sys
from datetime import datetime
from pathlib import Path

# Add the project root to Python path
project_root = Path(__file__).parent
sys.path.append(str(project_root))

from src.config import config
from src.storage import StorageManager
from expiry_db import ExpiryDatabase

def main():
    """Main cleanup function"""
    print("🧹 Sharey Cleanup Script (Database-driven)")
    print("=" * 50)
    print(f"⏰ Started at: {datetime.utcnow().isoformat()}")
    
    try:
        # Load configuration
        print("✅ Loaded configuration from config.json")
        
        # Initialize storage manager
        storage_manager = StorageManager(config)
        backend_info = storage_manager.get_backend_info()
        print(f"📁 Storage backend: {backend_info['type']}")
        
        # Initialize expiry database
        expiry_db = ExpiryDatabase()
        
        # Get expired files from database
        expired_files = expiry_db.get_expired_files()
        
        if not expired_files:
            print("✅ No expired files found.")
            return 0
        
        print(f"🗑️ Found {len(expired_files)} expired files to delete:")
        
        deleted_count = 0
        for file_info in expired_files:
            file_path = file_info['file_path']
            expires_at = file_info['expires_at']
            storage_backend = file_info['storage_backend']
            
            try:
                print(f"🗑️ Deleting expired file: {file_path} (expired: {expires_at})")
                
                # Delete from storage backend
                if storage_manager.delete_file(file_path):
                    # Remove from expiry database
                    expiry_db.remove_file(file_path)
                    deleted_count += 1
                    print(f"✅ Deleted: {file_path}")
                else:
                    print(f"❌ Failed to delete from storage: {file_path}")
                    
            except Exception as e:
                print(f"❌ Error deleting {file_path}: {e}")
        
        print("=" * 50)
        print(f"✅ Cleanup completed! Deleted {deleted_count} expired files.")
        
        # Show database stats
        stats = expiry_db.get_stats()
        print(f"📊 Database stats:")
        print(f"   • Total tracked files: {stats.get('total_files', 0)}")
        print(f"   • Active files: {stats.get('active_files', 0)}")
        print(f"   • Expired files: {stats.get('expired_files', 0)}")
        
        return deleted_count
        
    except Exception as e:
        print(f"❌ Cleanup failed: {e}")
        return -1
    
    finally:
        print(f"⏰ Finished at: {datetime.utcnow().isoformat()}")

if __name__ == "__main__":
    result = main()
    sys.exit(0 if result >= 0 else 1)
