import os
import hashlib
from flask import Flask, request, Response

app = Flask(__name__)

# Путь к папке с клиентом игры
GAME_DIR = '/var/www/html/World of Warcraft'

# Кэш MD5, чтобы не пересчитывать гигабайтные файлы при каждом запросе
MD5_CACHE = {}

def get_file_md5(file_path):
    if not os.path.isfile(file_path):
        return ""
    mtime = os.path.getmtime(file_path)
    if file_path in MD5_CACHE and MD5_CACHE[file_path]['mtime'] == mtime:
        return MD5_CACHE[file_path]['md5']
    
    hash_md5 = hashlib.md5()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(1024 * 1024 * 4), b""):
            hash_md5.update(chunk)
    
    calc_md5 = hash_md5.hexdigest().lower()
    MD5_CACHE[file_path] = {'mtime': mtime, 'md5': calc_md5}
    return calc_md5

@app.route('/updater', methods=['GET'])
def handle_updater():
    # 1. Запрос MD5 хеша конкретного файла (?md5=patches/Data/...)
    if 'md5' in request.args:
        rel_file = request.args.get('md5').replace('patches/', '').replace('patches_hd/', '')
        full_path = os.path.join(GAME_DIR, rel_file)
        return Response(get_file_md5(full_path), mimetype='text/plain')

    # 2. Запрос обычных патчей (?patches)
    if 'patches' in request.args:
        file_list = []
        for root, _, files in os.walk(GAME_DIR):
            for file in files:
                # Исключаем временные файлы и HD-модели (если разделяем)
                if file.endswith('.tmp') or file == 'Launcher.xml':
                    continue
                rel_path = os.path.relpath(os.path.join(root, file), GAME_DIR).replace('\\', '/')
                file_list.append(f"patches/{rel_path}")
        
        raw_text = "\n".join(file_list)
        hex_data = raw_text.encode('utf-8').hex()
        return Response(f"data={hex_data}", mimetype='text/plain')

    # 3. Запрос HD-патчей (?patches_hd)
    if 'patches_hd' in request.args:
        # Если все файлы уже включены в основной клиент, возвращаем пустую строку
        return Response("data=", mimetype='text/plain')

    return Response("Flygard Updater API Ready", mimetype='text/plain')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5005)