import os
import threading
import time
from datetime import datetime
import uuid

class DownloadManager:
    def __init__(self):
        self.active_downloads = {}
        self.download_history = []
        self.lock = threading.Lock()  # Add thread safety
    
    def create_download_id(self):
        return str(uuid.uuid4())
    
    def add_download(self, download_id, filename, status='pending'):
        with self.lock:
            self.active_downloads[download_id] = {
                'id': download_id,
                'filename': filename,
                'status': status,
                'progress': 0,
                'created_at': datetime.now(),
            }
    
    def update_progress(self, download_id, progress):
        with self.lock:
            if download_id in self.active_downloads:
                # Round progress to 2 decimal places
                self.active_downloads[download_id]['progress'] = round(progress, 2)
    
    def update_status(self, download_id, status):
        with self.lock:
            if download_id in self.active_downloads:
                self.active_downloads[download_id]['status'] = status
    
    def get_download(self, download_id):
        with self.lock:
            return self.active_downloads.get(download_id, {}).copy() if download_id in self.active_downloads else None
    
    def remove_download(self, download_id):
        with self.lock:
            if download_id in self.active_downloads:
                download = self.active_downloads.pop(download_id)
                self.download_history.append(download)
    
    def cleanup_old_files(self, download_path, max_age_hours=2):
        """Delete files older than max_age_hours"""
        now = time.time()
        max_age_seconds = max_age_hours * 3600
        
        if os.path.exists(download_path):
            for filename in os.listdir(download_path):
                filepath = os.path.join(download_path, filename)
                if os.path.isfile(filepath):
                    file_age = now - os.path.getmtime(filepath)
                    if file_age > max_age_seconds:
                        try:
                            os.remove(filepath)
                            print(f"Deleted old file: {filename}")
                        except Exception as e:
                            print(f"Error deleting {filename}: {e}")

# Global instance
download_manager = DownloadManager()