import os
import zipfile
from flask import Blueprint, render_template, send_from_directory, send_file, current_app

bp = Blueprint('mods', __name__, url_prefix='/mods')

# Minecraft 모드 디렉토리 경로
MODS_DIR = '/home/minecraft/server/mods/'

@bp.route('/')
def mods():
    """설치된 모드 목록을 보여주는 페이지."""
    try:
        # mods 디렉토리에서 .jar 파일 목록 가져오기
        mod_files = [file for file in os.listdir(MODS_DIR) if file.endswith('.jar')]
    except FileNotFoundError:
        mod_files = []  # 디렉토리가 없을 경우 빈 목록 반환

    return render_template('mods.html', mod_files=mod_files)

@bp.route('/download/<mod_name>')
def download_mod(mod_name):
    """모드 파일 다운로드."""
    try:
        return send_from_directory(MODS_DIR, mod_name, as_attachment=True)
    except FileNotFoundError:
        return "File not found", 404

@bp.route('/download-all')
def download_all_mods():
    """모든 모드 ZIP 파일 다운로드."""
    zip_filename = "all_mods.zip"
    zip_path = os.path.join(current_app.instance_path, zip_filename)

    try:
        # ZIP 파일 생성
        with zipfile.ZipFile(zip_path, 'w') as zipf:
            for file in os.listdir(MODS_DIR):
                if file.endswith('.jar'):
                    zipf.write(os.path.join(MODS_DIR, file), arcname=file)

        return send_file(zip_path, as_attachment=True)

    except Exception as e:
        current_app.logger.error(f"Error creating ZIP file: {e}")
        return "Error creating ZIP file", 500

    finally:
        # ZIP 파일 삭제 (일회성 제공)
        if os.path.exists(zip_path):
            os.remove(zip_path)
