# flask_app/routes/get_deviation.py
import json

from flask import Blueprint, Response, g
import os
from flask_app.general.format_change import download_file
from flask_app.routes.偏离表数据解析main import get_tech_and_business_deviation
from flask_app.routes.utils import generate_deviation_response, validate_and_setup_logger, create_response, sse_format, \
    log_error_unique_id
from flask_app.ConnectionLimiter import require_connection_limit, require_execution_timeout

get_deviation_bp = Blueprint('get_deviation', __name__)

@get_deviation_bp.route('/get_deviation', methods=['POST'])
@validate_and_setup_logger
# @require_connection_limit(timeout=1800)
@require_execution_timeout(timeout=1800)
def get_deviation():                  #提供商务、技术偏离的数据
    logger = g.logger
    unique_id = g.unique_id
    file_url = g.file_url
    zb_type = g.zb_type
    output_folder = g.output_folder
    def generate():
        try:
            logger.info("call /get_deviation: 开始解析 URL: " + file_url)
            if zb_type not in [1, 2, 3]:
                logger.error(f"无效的 zb_type: {zb_type}. 期望 zb_type: 1 或 2")
                log_error_unique_id(unique_id, 3)
                response = create_response(
                    message='此端点仅支持 zb_type 1 或 2',
                    status='error',
                    data=''
                )
                yield sse_format(response)
                return  # 终止生成器
            # 映射 zb_type，如果是 3 则映射为 2
            mapped_zb_type = 2 if zb_type == 3 else zb_type
            # 直接下载并处理文件
            filename = "ztbfile"
            downloaded_filename = os.path.join(output_folder, filename)
            # 下载文件
            downloaded_filepath, file_type = download_file(file_url, downloaded_filename)
            if downloaded_filepath is None or file_type == 4:
                logger.error("下载地址不存在或不支持的文件类型！")
                log_error_unique_id(unique_id, 3)
                response = create_response(
                    message='下载地址不存在或不支持的文件类型！',
                    status='error',
                    data=''
                )
                yield sse_format(response)
                return  # 终止生成器

            logger.info("Local file path: " + downloaded_filepath)

            # 处理文件
            deviations = get_tech_and_business_deviation(
                downloaded_filepath, file_type, unique_id, output_folder, mapped_zb_type
            )

            if deviations is None:
                logger.info(f"服务器内部出错！")
                log_error_unique_id(unique_id, 3)
                response = create_response(
                    message='服务器内部出错！',
                    status='error',
                    data=''
                )
                yield sse_format(response)
                return  # 终止生成器

            # 解包返回值
            (tech_deviation, tech_star_deviation, business_deviation,
             business_star_deviation, zigefuhe_deviation, proof_materials,technical_standards) = deviations

            # 生成偏差响应
            tech_deviation_response, tech_deviation_star_response, zigefuhe_deviation_response, \
                shangwu_deviation_response, shangwu_star_deviation_response, proof_materials_response = generate_deviation_response(
                tech_deviation, tech_star_deviation, business_deviation,
                business_star_deviation, zigefuhe_deviation, proof_materials, logger
            )

            final_response = {
                'message': 'processed successfully',
                'status': 'success',
                'data': 'END'
            }
            # logger.info(f"技术评分: {json.dumps(technical_standards, ensure_ascii=False, indent=4)}")

            technical_standards_response = {
                'message': 'tech_evaluation',
                'status': 'success',
                'data': json.dumps(technical_standards, ensure_ascii=False)
            }
            # 流式返回数据
            yield sse_format(tech_deviation_response)
            yield sse_format(tech_deviation_star_response)
            yield sse_format(zigefuhe_deviation_response)
            yield sse_format(shangwu_deviation_response)
            yield sse_format(shangwu_star_deviation_response)
            yield sse_format(proof_materials_response)
            # yield sse_format(technical_standards_response)
            yield sse_format(final_response)

        except Exception as e:
            logger.error('服务器内部发生异常: ' + str(e))
            log_error_unique_id(unique_id, 3)
            response = create_response(
                message=str(e),
                status='error',
                data=''
            )
            yield sse_format(response)

    return Response(generate(), mimetype='text/event-stream')


