import time
import numpy as np
from params import configs
from CPSolver import CPSolver
from uniform_instance_gen import uni_instance_gen


if __name__ == '__main__':
    # 重复10次生成，每次CP运行时间1小时（3600秒），取平均值
    N = configs.test_GenData_N
    m = configs.gen_machine_num
    BWS = False  # 是否使用阻塞约束的严格等式版，和现有脚本保持一致
    
    print(f"开始CP求解器重复测试 (N={N}, M={m}, 重复10次, 每次上限=3600s)...")
    
    makespan_list = []
    elapsed_list = []
    
    for i in range(1):
        print(f"\n=== 第 {i+1}/10 次测试 ===")
        
        # 每次使用不同的随机种子
        np.random.seed(i)
        times, machines = uni_instance_gen(N, m, 1, 100)
        data = (times, machines)

        cp_solver = CPSolver()
        start_time = time.time()
        schedule = cp_solver.solve_blocking_job_shop(
            data,
            mask=None,
            random_seed=2025 + i,  # 每次使用不同的随机种子
            time_limit=36 * N ,  # 10小时
            bws=BWS
        )
        elapsed = time.time() - start_time
        makespan = schedule.cal_makespan()
        
        makespan_list.append(makespan)
        elapsed_list.append(elapsed)
        
        print(f"第{i+1}次: makespan={makespan}, 用时={elapsed:.2f}秒")
    
    # 计算平均值和统计信息
    avg_makespan = np.mean(makespan_list)
    avg_elapsed = np.mean(elapsed_list)
    std_makespan = np.std(makespan_list)
    std_elapsed = np.std(elapsed_list)
    
    print(f"\n=== 测试结果统计 ===")
    print(f"平均makespan: {avg_makespan:.2f} (±{std_makespan:.2f})")
    print(f"平均用时: {avg_elapsed:.2f}秒 (±{std_elapsed:.2f}秒)")
    print(f"makespan范围: [{min(makespan_list):.2f}, {max(makespan_list):.2f}]")
    print(f"用时范围: [{min(elapsed_list):.2f}, {max(elapsed_list):.2f}]秒")
    
    # 如需可视化甘特图可解除下行注释（显示最后一次的结果）
    # schedule.plotSchedule(data)

