import os, sys, argparse, json
import importlib.util
# 添加上级目录到 sys.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))

from Initial_Alg_Program.Initial_Alg_Select_Tool import select_crop_size, select_pretrained_model, select_sampler

from Initial_Alg_Program.Initial_Alg_Gen_Tool import format_all_data, write_config_to_file, create_dict_by_kwargs, get_var_from_file, update_list_dict_var, get_var_from_py_file
from Initial_Alg_Program.Initial_Alg_Gen_0_base_ import generate_base_config
from Initial_Alg_Program.Initial_Alg_Gen_1_norm_cfg import generate_norm_cfg
from Initial_Alg_Program.Initial_Alg_Gen_2_data_preprocessor import generate_data_preprocessor
from Initial_Alg_Program.Initial_Alg_Gen_3_model import generate_model_pretrained, generate_model_backbone, generate_model_data_preprocessor, generate_model_decode_head, generate_model_auxiliary_head, generate_model_train_cfg, generate_model_test_cfg
from Initial_Alg_Program.Initial_Alg_Gen_4_optimizer import generate_optim_wrapper, generate_param_scheduler

if __name__ == '__main__':
    ########### 1.超参数-算法默认参数 ###########
    alg_file_name = 'ddrnet'
    alg_file_pth = f"configs/_base_/models/{alg_file_name}.py"

    ########### 2.参数解析 ########### 
    parser = argparse.ArgumentParser(description="Run algorithm with specified parameters.")

    # 添加命令行参数
    parser.add_argument('--alg_name', type=str, required=True, help="Algorithm name (e.g., 'ann')")
    parser.add_argument('--dataset_file_name', type=str, required=True, help="Dataset file name (e.g., 'my_dataset_model')")
    parser.add_argument('--mean', type=str, required=True, help="Mean of dataset (e.g., [1.2, 1.2, 1.2])")
    parser.add_argument('--std', type=str, required=True, help="Mean of dataset (e.g., [1.2, 1.2, 1.2])")
    parser.add_argument('--dataset_num_classes', type=int, required=True, help="Dataset class num (e.g., 36)")
    parser.add_argument('--GPU_num', type=int, required=True, help="Num of GPU to train (e.g., 1)")
    parser.add_argument('--schedule_file_name', type=str, required=True, help="Schedule file name (e.g., 'schedule_4k_check_400')")
    parser.add_argument('--train_type', type=str, required=True, help="Schedule train type (e.g., Epoch or Iteration)")
    parser.add_argument('--train_time_or_epoch_k', type=int, required=True, help="Schedule train time k (e.g., 4)")

    # 解析命令行参数
    args = parser.parse_args()

    # 变量赋值
    alg_name = args.alg_name
    dataset_file_name = args.dataset_file_name
    mean = json.loads(args.mean) # 使用json.loads转换成list
    std = json.loads(args.std) # 使用json.loads转换成list
    num_classes = args.dataset_num_classes
    schedule_file_name = args.schedule_file_name
    train_type = args.train_type
    train_time_or_epoch_k = args.train_time_or_epoch_k
    GPU_num = args.GPU_num

    ########### 3.1. 生成_base_部分 ########### 
    _base_ = generate_base_config(alg_file_name=alg_file_name, dataset_file_name=dataset_file_name, schedule_file_name=schedule_file_name)

    ########### 3.1. 生成norm_cfg部分 ########### 
    norm_cfg = generate_norm_cfg(GPU_num=GPU_num)

    ########### 3.2. 生成data_preprocessor部分 ########### 
    crop_size = select_crop_size(predefined_options=[(512, 512)]) # 选择切割大小
    data_preprocessor = generate_data_preprocessor(crop_size = crop_size, mean = mean, std = std)

    ########### 3.3. 生成model部分 ########### 
    # 3.3.1. 预处理data_preprocessor
    model_data_preprocessor = data_preprocessor # 修改data_preprocessor

    # # 3.3.2. 骨架backbone、解码器decode_head
    model_list = ["openmmlab/ddrnet23-s", "openmmlab/ddrnet23"] 
    selected_model_name, select_pretrained, pretrained_pth, selected_model_info = select_pretrained_model(model_list=model_list)
    if selected_model_name == "openmmlab/ddrnet23-s":
        backbone = dict(channels=32, init_cfg=dict(type='Pretrained', checkpoint=pretrained_pth))
        decode_head = dict(in_channels=32 * 4, channels=64, num_classes=num_classes)
        model_size = 'small'
    elif selected_model_name == "openmmlab/ddrnet23":
        backbone = dict(channels=64, init_cfg=dict(type='Pretrained', checkpoint=pretrained_pth))
        decode_head = dict(in_channels=64 * 4, channels=128, num_classes=num_classes)
        model_size = 'normal'
    else:
        quit("Error: 未知的模型名称")

    # 3.3.4. 综合model
    model = dict(
        data_preprocessor = model_data_preprocessor,
        backbone = backbone,
        decode_head = decode_head,
    )

    ########### 3.4. 生成optim、param_scheduler部分 ########### 
    optim_wrapper = generate_optim_wrapper()
    param_scheduler = generate_param_scheduler(train_type, train_time_or_epoch_k)

    ########### 4.程序写入 ###########
    # 4.1. 算法名称解析：bisenetv2【Alg】 _ r50【pretrained模型深度】 - d8【_base_/models】 _ 4【GPU数量】 x b2【Batch Size大小】 - 40k【schedule】 _ cityscapes【数据集】 - 512x1024【crop_size】.py
    alg_file_name = f"{alg_name}_{model_size}_g{GPU_num}-{schedule_file_name.lstrip('schedule_')}_{dataset_file_name}-{crop_size[0]}x{crop_size[1]}.py"
    output_configs_alg_my_alg = os.path.join(f'./configs/ddrnet/', alg_file_name)
    write_config_to_file(output_configs_alg_my_alg, _base_=_base_, norm_cfg=norm_cfg, crop_size=crop_size, data_preprocessor=data_preprocessor, model=model, optim_wrapper=optim_wrapper, param_scheduler=param_scheduler)

    # 4.2. 将信息临时写入文件
    with open("_temp_.txt", "w") as file:
        json.dump({'alg_infos':{'alg_file_name':alg_file_name,'alg_file_pth':output_configs_alg_my_alg}}, file)
