# flask_app/start_up.py
import os

from flask import Flask, g
from flask_app.ConnectionLimiter import ConnectionLimiter
from flask_app.logger_setup import create_logger_main
from flask_app.routes.get_deviation import get_deviation_bp
from flask_app.routes.little_zbparse import little_zbparse_bp
from flask_app.routes.test_readpdf import test_readpdf_bp
from flask_app.routes.upload import upload_bp
from flask_app.routes.test_zbparse import test_zbparse_bp
from flask_app.general.llm.清除file_id import delete_file_by_ids,read_file_ids
from flask_app.routes.judge_zbfile import judge_zbfile_bp
from flask_app.routes.test_preprocess import test_process_bp


def create_app():
    # 创建全局日志记录器
    app = Flask(__name__)
    app.global_logger = create_logger_main('model_log')  # 全局日志记录器
    # 注册蓝图
    app.register_blueprint(get_deviation_bp)
    app.register_blueprint(little_zbparse_bp)
    app.register_blueprint(upload_bp)
    app.register_blueprint(test_zbparse_bp)
    app.register_blueprint(judge_zbfile_bp)
    app.register_blueprint(test_process_bp)
    app.register_blueprint(test_readpdf_bp)
    @app.teardown_request
    def teardown_request(exception):
        output_folder = getattr(g, 'output_folder', None)
        # 接口请求之后都会执行该代码，做一些清理工作
        logger = getattr(g, 'logger', None)
        if output_folder:
            # 执行与output_folder相关的清理操作（例如删除临时文件）
            logger.info(f"正在清理输出文件夹: {output_folder}")
            file_ids = read_file_ids(output_folder)
            failed_file_ids = delete_file_by_ids(file_ids)
            if failed_file_ids:
                logger.error(f"以下文件删除失败: {failed_file_ids}")
            else:
                logger.info("清理完毕！")
        if logger:
            for handler in logger.handlers[:]:
                handler.close()
                logger.removeHandler(handler)
    return app


if __name__ == '__main__':
    app = create_app()
    app.run(debug=True, host='0.0.0.0', port=5000)
