# 批处理文档
import os
import re
import sys
import time

sys.path.append("../..")
import traceback
import concurrent.futures

from loguru import logger

from utils.common_util import random_str
from utils.http_util import upload_file, fastgpt_openai_chat, download_file

use_lufa = False
batch_size = 5

if not use_lufa:
    SUFFIX = "_麓发迁移"
    batch_input_dir_path = "jp-input"
    batch_output_dir_path = f"/home/ccran/lufa-contract/data/benchmark/results/jp-output-lufa-{time.strftime('%Y%m%d-%H%M%S', time.localtime())}"
    # 金盘fastgpt接口
    url = "http://192.168.252.71:18088/api/v1/chat/completions"
    # 金盘迁移麓发合同审查测试token
    token = "fastgpt-vykT6qs07g7hR4tL2MNJE6DdNCIxaQjEu3Cxw9nuTBFg8MAG3CkByvnXKxSNEyMK7"
    # 人机交互测试（测试环境）
    # token = 'fastgpt-p189K5zoTX5wjp0dBybFCwsbWm3juIwlJxt2wTGyiaOWOANI5Y10pKEZzyt'
    # 人机交互测试（生产环境）
    # token = "fastgpt-ry4jIjgNwmNgufMr5jR0ncvJVmSS4GZl4bx2ItsNPoncdQzW9Na3IP1Xrankr"
    # 提取后审查测试
    # token = 'fastgpt-n74gGX5ZqLT6o1ysMBSGUTjIciswYOWDRfQ75krMkE5gDVDkpzsbz8u'
else:
    SUFFIX = "_麓发"
    batch_input_dir_path = "4.24测财务合同审核"
    batch_output_dir_path = "4.24测财务合同审核-batch"
    # 麓发fastgpt接口
    url = "http://192.168.252.71:18089/api/v1/chat/completions"
    # 麓发合同审查生产token
    # token = "fastgpt-ek3Z6PxI6sXgYc0jxzZ5bVGqrxwM6aVyfSmA6JVErJYBMr2KmYxrHwEUOIMSYz"
    # 麓发合同审查生产token-标准化
    token = "fastgpt-mg5tQUgreJeF7peoOr5zqP0NR4EIrfS2bEVXge6FUL94Suu1TvEMR1sGNRSiV"


def extract_url(text):
    # \s * ([ ^ "\s]+?\.(?:docx?|pdf|xlsx))
    excel_p, doc_p = (
        r'最终审查Excel\s*([^"]*xlsx)',
        r"最终审查批注\s*([^\" ]+?\.(?:docx?|pdf|wps))",
    )
    # 使用 re.search() 查找第一个匹配项
    excel_m, doc_m = re.search(excel_p, text), re.search(doc_p, text)
    if excel_m and doc_m:
        # 提取匹配的 url 部分
        return excel_m.group(1), doc_m.group(1)
    else:
        return None, None


def process_single_file(
    file, batch_input_dir_path, batch_output_dir_path, counter, start_file
):
    """
    单文件处理逻辑，可被线程池并发调用
    """
    # 文件跳过
    if start_file > counter:
        return

    # 提取文件前缀
    file_name = file[: file.rfind(".")]
    ext_name = file[file.rfind(".") :]
    # 源目标处理
    original_file = f"{batch_input_dir_path}/{file}"
    des_check_file = f"{batch_output_dir_path}/{file_name}.md"
    des_excel_file = f"{batch_output_dir_path}/{file_name}{SUFFIX}.xlsx"
    des_doc_file = f"{batch_output_dir_path}/{file_name}{SUFFIX}{ext_name}"

    try:
        # 处理原文件
        file_url = upload_file(original_file, input_url_to_inner=True).replace(
            "218.77.58.8", "192.168.252.71"
        )
        model = "Qwen2-72B-Instruct"
        # 合同审核Excel工作流处理
        logger.info(" 第{}个文件,处理文件: {}".format(counter, original_file))

        result = fastgpt_openai_chat(
            url,
            token,
            model,
            random_str(),
            file_url,
            f"测试批处理任务-{file_name}",
            False,
        )
        excel_url, doc_url = extract_url(result)
        if excel_url and doc_url:
            download_file(
                excel_url.replace("218.77.58.8", "192.168.252.71").replace(
                    "znkf.lgfzgroup.com", "192.168.252.71"
                ),
                des_excel_file,
            )
            download_file(
                doc_url.replace("218.77.58.8", "192.168.252.71").replace(
                    "znkf.lgfzgroup.com", "192.168.252.71"
                ),
                des_doc_file,
            )
            logger.info(
                f"第{counter}个文件下载:{excel_url}到{des_excel_file} {des_doc_file}"
            )
    except Exception as e:
        logger.error(f"{original_file} 处理异常 第{counter}个文件: {e}")
        logger.error(traceback.print_exc())


def execute_batch(max_workers: int = 4):
    start_file = 1
    dirs = os.listdir(batch_input_dir_path)
    os.makedirs(batch_output_dir_path, exist_ok=True)

    with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = [
            executor.submit(
                process_single_file,
                file,
                batch_input_dir_path,
                batch_output_dir_path,
                counter,
                start_file,
            )
            for counter, file in enumerate(dirs, start=1)
        ]
        # 确保异常能在主线程抛出
        for f in concurrent.futures.as_completed(futures):
            f.result()


if __name__ == "__main__":
    import os

    execute_batch(batch_size)
    print("all done!")
    print("文件保存在: ", os.path.abspath(batch_output_dir_path))
