# : run_batch_experiments.py

import os
import subprocess

# --- 1.  ---

# ---  DATASETS_TO_TEST  ---
DATASETS_TO_TEST = []
lag, noise_level, function_type, noise_function_type, intervention_history, is_history_dep, connection_factor = 2, 0.5, "mlp", "spline_product", 3, True, 2
seeds_to_test = range(6)
nodes_to_test = [5, 10, 20]
graph_types_to_test = ["ER", "SF"]

for seed in seeds_to_test:
    for num_nodes in nodes_to_test:
        for graph_type in graph_types_to_test:
            inst_graph_type = lag_graph_type = graph_type
            dataset_name = (
                f"{inst_graph_type}_{lag_graph_type}_lag_{lag}_dim_{num_nodes}"
                f"_HistDep_{noise_level}_{function_type}_{noise_function_type}"
                f"_con_{connection_factor}_inthist_{intervention_history}_seed_{seed}"
            )
            DATASETS_TO_TEST.append(dataset_name)

print(f" {len(DATASETS_TO_TEST)} 。")
# ---  ---

# 
PRIOR_RATES = [0.0, 0.05, 0.1, 0.3, 0.5]

# 
DEVICE = "gpu"


# ---  ---

def main():
    """，，"""
    total_datasets = len(DATASETS_TO_TEST)
    print(f"， {total_datasets} 。")
    print("=" * 70)

    for i, dataset_name in enumerate(DATASETS_TO_TEST):
        print(f"-->  {i+1}/{total_datasets}: {dataset_name}")
        
        dataset_path = os.path.join("data", dataset_name)
        if not os.path.isdir(dataset_path):
            print(f"[] : {dataset_path}。。")
            print("-" * 70)
            continue

        # --- 【】:  ---
        print(f"  - ...")
        for rate in PRIOR_RATES:
            if rate is None:
                continue # None rate 
            
            rate_str = str(float(rate))
            mask_path = os.path.join(dataset_path, f"exist_mask_{rate_str}.npy")

            if not os.path.exists(mask_path):
                print(f"    - : {mask_path}。...")
                
                create_prior_command = [
                    "python", "generate_prior.py",
                    "--path", dataset_path,
                    "--strength", str(rate)
                ]

                try:
                    #  check=True ，
                    subprocess.run(create_prior_command, check=True, capture_output=True, text=True)
                    print(f"    - 。")
                except subprocess.CalledProcessError as e:
                    print(f"[] ！")
                    print(f"  - : {' '.join(create_prior_command)}")
                    print(f"  - :\n{e.stderr}")
                    print(f"  - 。")
                    #  break ，
                    break 
            # else:
            #     print(f"    - : {mask_path}") # 
        else: #  else  for ， for （ break）
            print("  - /。")
            # --- 【】 ---

            # ---  ---
            for rate in PRIOR_RATES:
                if rate is None:
                    mask_path_arg = "None"
                    print(f"\n---  () ---")
                else:
                    rate_str = str(float(rate)) 
                    mask_path_arg = os.path.join(dataset_path, f"exist_mask_{rate_str}.npy")
                    print(f"\n---  (: {rate*100}%) ---")

                    if not os.path.exists(mask_path_arg):
                        print(f"[] : {mask_path_arg}。。")
                        continue
                
                command_to_run = [
                    "python", "run_single_experiment.py",
                    dataset_name,
                    mask_path_arg,
                    "--device", DEVICE
                ]
                
                print(f"  - : {' '.join(command_to_run)}")
                try:
                    subprocess.run(command_to_run, check=True)
                except subprocess.CalledProcessError:
                    print(f"[]  run_single_experiment.py 。")
                    print(f"  - : {dataset_name}, : {mask_path_arg}")
                    print("。")
                    return
        
        print(f"<--  {dataset_name} 。")
        print("=" * 70)

    print("！")


if __name__ == "__main__":
    main()