from flask import Flask, request, jsonify, send_from_directory
import csv, os
import config

app = Flask(__name__)

# 读取 CSV 文件
def read_csv(file_path):
    if not os.path.exists(file_path):
        return []
    with open(file_path, newline='', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        return list(reader)

# 写入 CSV 文件
def write_csv(file_path, fieldnames, rows):
    os.makedirs(os.path.dirname(file_path) or ".", exist_ok=True)
    with open(file_path, 'w', newline='', encoding='utf-8') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)

# 获取服务器镜像列表
@app.route("/api/images")
def get_images():
    data = read_csv(config.SERVER_FILE)
    for d in data:
        d["download_url"] = f"/images/{d['image_path']}"
    return jsonify(data)

# 接收客户端上报
@app.route("/api/client/update", methods=["POST"])
def update_client():
    data = request.json
    client_id = data.get("client_id")
    images = data.get("images", [])
    if not client_id or not images:
        return jsonify({"status":"error","msg":"Invalid data"}), 400

    # 读取原有客户端 CSV
    client_data = read_csv(config.CLIENT_FILE)
    client_dict = { row['image_name'] + "_" + row.get("client_id",""): row for row in client_data }

    for img in images:
        key = img["image_name"] + "_" + client_id
        client_dict[key] = {
            "client_id": client_id,
            "image_name": img["image_name"],
            "image_tag": img["image_tag"],
            "last_updated": img["last_updated"]
        }

    # 写回 CSV
    write_csv(config.CLIENT_FILE, config.CLIENT_FIELDS, list(client_dict.values()))
    return jsonify({"status":"ok"})

# 提供镜像下载
@app.route("/images/<path:filename>")
def serve_image(filename):
    return send_from_directory(config.IMG_DIR, filename)

if __name__ == "__main__":
    # 确保 CSV 文件存在
    if not os.path.exists(config.SERVER_FILE):
        write_csv(config.SERVER_FILE, config.SERVER_FIELDS, [])
    if not os.path.exists(config.CLIENT_FILE):
        write_csv(config.CLIENT_FILE, config.CLIENT_FIELDS, [])

    # 确保镜像目录存在
    os.makedirs(config.IMG_DIR, exist_ok=True)

    app.run(host=config.HOST, port=config.PORT, debug=config.DEBUG)
