"""
Storage Cleanup Module
Handles proper cleanup and memory management for storage operations
"""

import os
import time
import sqlite3
import time
import sqlite3
from typing import Optional
from pathlib import Path

class StorageCleanup:
    """
    Manages cleanup operations for storage and memory management
    """
    
    def __init__(self, storage_path: str):
        self.storage_path = storage_path
        self.last_cleanup = time.time()
        self.cleanup_interval = 60  # Cleanup every 60 seconds
        
    def cleanup_storage(self):
        """
        Performs storage cleanup operations:
        - Vacuum SQLite database
        - Remove temporary files
        - Clear any lingering connections
        """
        try:
            # Connect with immediate mode for faster cleanup
            conn = sqlite3.connect(self.storage_path, isolation_level=None)
            conn.execute("PRAGMA temp_store = MEMORY;")  # Store temp tables in memory
            conn.execute("PRAGMA journal_mode = OFF;")   # Disable journaling for cleanup
            conn.execute("VACUUM;")  # Compact the database
            conn.close()
            
        except Exception as e:
            print(f"Cleanup error: {e}")
            
    def cleanup_if_needed(self):
        """Check if cleanup is needed based on interval"""
        current_time = time.time()
        if current_time - self.last_cleanup >= self.cleanup_interval:
            self.cleanup_storage()
            self.last_cleanup = current_time
            
    @staticmethod
    def force_release_memory():
        """Force memory release"""
        pass  # Memory management handled by Python runtime