from flask import Flask, request, jsonify
import json
import os

app = Flask(__name__)
LEADERBOARD_FILE = "../leaderboard.json"

# 加载排行榜数据
def load_leaderboard():
    if os.path.exists(LEADERBOARD_FILE):
        with open(LEADERBOARD_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    return []

# 保存排行榜数据
def save_leaderboard(data):
    with open(LEADERBOARD_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

# 获取排行榜
@app.route("/get_board", methods=["GET"])
def get_board():
    return jsonify(load_leaderboard())

# 上传排行榜
@app.route("/set_board", methods=["POST"])
def set_board():
    try:
        data = request.json
        save_leaderboard(data)
        return jsonify(data)  # 直接返回排行榜
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 400


if __name__ == "__main__":
    app.run(debug=True, port=5000)
