import os
import uuid
from datetime import datetime
from werkzeug.utils import secure_filename
from config import Config

class FileHandler:
    ALLOWED_EXTENSIONS = {
        'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 
        'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx',
        'mp3', 'mp4', 'zip', 'rar'
    }
    
    @staticmethod
    def allowed_file(filename):
        return '.' in filename and \
               filename.rsplit('.', 1)[1].lower() in FileHandler.ALLOWED_EXTENSIONS
    
    @staticmethod
    def save_file(file, uploader_account):
        """保存上传的文件"""
        if file and FileHandler.allowed_file(file.filename):
            # 生成唯一文件名
            filename = secure_filename(file.filename)
            unique_filename = f"{uuid.uuid4().hex}_{filename}"
            
            # 保存文件
            # 确保上传目录存在
            os.makedirs(Config.UPLOAD_FOLDER, exist_ok=True)

            file_path = os.path.join(Config.UPLOAD_FOLDER, unique_filename)
            file.save(file_path)
            
            # 返回文件信息（包含兼容键名）
            return {
                'filename': filename,
                'original_name': filename,
                'saved_name': unique_filename,
                'size': os.path.getsize(file_path),
                'uploader': uploader_account,
                'upload_time': datetime.now(),
                'url': f'/static/uploads/{unique_filename}'
            }
        return None