import os
import json
import time
from datetime import datetime
from flask import Flask, request, jsonify

app = Flask(__name__)
# 文件保存路径
SAVE_DIR = "/data/news/learn_records/"

@app.route('/save', methods=['POST'])
def json_string():
    data = request.get_json()
    if data is None:
        return jsonify({"msg": "请求体不是合法的 JSON"}), 400
    content = data.get('content')
    uuid = data.get('uuid')
    try:
        content_json = json.loads(content)
        # ✅ 关键修复：只允许 对象（dict）或 数组（list）
        if not isinstance(content_json, (dict, list)):
            return jsonify({"msg": "JSON格式错误"}), 400
    except Exception as e:
        print(e)
        return jsonify({"msg": "JSON格式错误"}), 400
    date_str = datetime.now().strftime("%Y%m%d")
    timestamp = str(int(time.time()))
    # 文件名 日期_10位时间戳.json
    filename = f"{uuid}_{date_str}_{timestamp}.json"
    file_path = os.path.join(SAVE_DIR, filename)
    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump(content_json, f, ensure_ascii=False, indent=2)
        # 返回成功信息
    return jsonify({
        "msg": "保存成功",
        "file": filename,
        "path": file_path
    }), 200

if __name__ == '__main__':
    # 启动服务，默认监听 0.0.0.0:5000
    app.run(host='0.0.0.0', port=8080, debug=True)