# flask_app/start_up.py

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.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


class FlaskAppWithLimiter(Flask):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 初始化一个字典来存储每个蓝图的限流器
        self.connection_limiters = {}


def create_app():
    app = FlaskAppWithLimiter(__name__)
    # 创建全局日志记录器
    app.global_logger = create_logger_main('global_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.connection_limiters['upload'] = ConnectionLimiter(max_connections=100)
    # app.connection_limiters['get_deviation'] = ConnectionLimiter(max_connections=100)
    # app.connection_limiters['default'] = ConnectionLimiter(max_connections=100)
    # app.connection_limiters['judge_zbfile'] = ConnectionLimiter(max_connections=100)

    # @app.teardown_request
    # def teardown_request(exception):
    #     # 接口请求之后都会执行该代码，做一些清理工作
    #     output_folder = getattr(g, 'output_folder', None)
    #     if output_folder:
    #         # 执行与output_folder相关的清理操作（例如删除临时文件）
    #         logger = g.logger  # 使用 app 的 logger
    #         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("清理完毕！")
    return app


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