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/"
# 文件读取路径
GET_DIR = "/data/news/json/origin_data/"
# 文件读取路径
GET_LEARNDIR = "/data/news/learn_records/"


# 文件后缀
FILE_SUFFIX = ".json"


@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')
    if not content or content.strip() == '':
        return jsonify({"msg": "content字段不能为空"}), 400
    uuid = data.get('uuid')
    custom_file = data.get('file')
    try:
        content_json = json.loads(content)
        if not isinstance(content_json, (dict, list)):
            return jsonify({"msg": "JSON格式错误"}), 400
    except Exception as e:
        print(e)
        return jsonify({"msg": "JSON格式错误"}), 400
    # 如果file字段不为空 则直接将内容写入file字段传入的文件名相应的文件
    if custom_file is not None and custom_file.strip() != '':
        # 统计目录下已有几个 {custom_file} 开头的文件，序号+1
        existing = [f for f in os.listdir(SAVE_DIR) if f.startswith(custom_file) and f.endswith(FILE_SUFFIX)]
        idx = len(existing) + 1
        filename = f"{custom_file}_{idx}{FILE_SUFFIX}"
        file_path = os.path.join(SAVE_DIR, filename)
    else:
        date_str = datetime.now().strftime("%m%d")
        timestamp = str(int(time.time()))
        # 文件名 日期_10位时间戳.json
        filename = f"{date_str}data{FILE_SUFFIX}"
        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)
    # 删除文件后缀
    file = filename.removesuffix(FILE_SUFFIX)
    return jsonify({
        "msg": "保存成功",
        "file": file,
        "path": file_path
    }), 200


@app.route('/dailydata', methods=['GET'])
def daily_data():
    date = request.args.get('date')
    type_param = request.args.get('type')
    # 处理 learn 类型
    if type_param == 'learn':
        # h获取file值
        file = request.args.get('file')
        if not file:
            return jsonify({"msg": "缺少 file 参数"}), 400
        # 拼接文件名+后缀
        filename = f"{file}{FILE_SUFFIX}"
        # 拼接文件路径
        file_path = os.path.join(GET_LEARNDIR, filename)
    else:
        # 如果date 为空 则 使用当前时间
        if not date or date.strip() == '':
            date = datetime.now().strftime('%m%d')
            date = f"{date}data"
        elif len(date) == 4:
            date = f"{date}data"
        else:
            date = f"{date}"
        # 拼接文件名+后缀
        filename = f"{date}{FILE_SUFFIX}"
        # 拼接文件路径
        file_path = os.path.join(GET_DIR, filename)
    # 统一文件读取
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            try:
                # json文件为空返回数据为抓取完成
                content = f.read()
                if content in (None, ""):
                    return jsonify({"msg": "今日数据未抓取完成"}), 400
                data = json.loads(content)
                if not isinstance(data, (dict, list)):
                    return jsonify({"msg": "文件中JSON格式错误"}), 400
            except json.JSONDecodeError:
                return jsonify({"msg": "文件中JSON格式错误"}), 400
        return data
    # json文件不存在返回数据为抓取完成
    except FileNotFoundError:
        return jsonify({"msg": "今日数据未抓取完成!"}), 400


if __name__ == '__main__':
    # 启动服务，默认监听 0.0.0.0:5000
    app.run(host='0.0.0.0', port=5000, debug=False)
