import os

from flask import request, jsonify, Blueprint, g
import uuid
import time
from flask_app.ConnectionLimiter import require_execution_timeout
from flask_app.general.format_change import download_file
from flask_app.routes.utils import validate_and_setup_logger
from flask_app.routes.货物标解析main import preprocess_files


test_process_bp = Blueprint('test_process', __name__)
@test_process_bp.route('/test_process', methods=['POST'])
@validate_and_setup_logger
@require_execution_timeout(timeout=1800)
def process_file():
    logger = g.logger
    output_folder = g.output_folder
    try:
        # 解析请求参数
        data = request.json
        file_url = data.get('file_url')
        # 参数校验
        if not file_url:
            return jsonify({'error': 'Missing file_url parameter'})

        # 生成唯一文件名
        filename = os.path.join(output_folder,'ztbfile.pdf')
        file_path,file_type=download_file(file_url, filename)
        # print(file_path)
        # 调用预处理函数
        start_time = time.time()
        result = preprocess_files(
            output_folder=output_folder,
            file_path=file_path,
            file_type=file_type,
            logger=logger
        )

        # 处理结果
        if not result:
            return jsonify({'error': 'File processing failed'})

        # 构造响应数据（根据实际需要调整返回字段）
        response_data = {
            'processing_time': f"{time.time() - start_time:.2f}s",
            'result': {
                'procurement_spec': result['procurement_path'],
                'evaluation_method': result['evaluation_method_path'],
                'qualification_docs': result['qualification_path'],
                'notice_docs': result['notice_path'],
                'clause_details': result['clause_path'],
                'merged_baseinfo': result['merged_baseinfo_path']
            }
        }

        return jsonify(response_data)

    except Exception as e:
        # app.logger.error(f"Processing error: {str(e)}")
        return jsonify({'error': f'Internal server error: {str(e)}'})
