import os, sys, argparse, json
# 添加上级目录到 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_test_cfg_slide

from Initial_Alg_Program.Initial_Alg_Gen_Tool import format_all_data, write_config_to_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 = 'danet_r50-d8'

    ########### 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. 设定参数 ########### 
    # 3.1. 自选参数
    crop_size = select_crop_size(predefined_options=[(512, 512), (512, 1024), (769, 769)]) # 选择切割大小
    model_list = ['openmmlab/resnet50_v1c', 'openmmlab/resnet101_v1c'] 
    selected_model_name, select_pretrained, pretrained_pth, selected_model_info = select_pretrained_model(model_list=model_list)
    depth = selected_model_info['depth']

    test_cfg_mode, test_cfg_crop_div_stride = select_test_cfg_slide(crop_size)

    # 3.2. 自动生成参数
    # decode、auxiliary损失下载方式
    decode_head_loss_decode_dict=dict(type='DiceLoss', use_sigmoid=False, loss_weight=1.0) # decode损失函数 # TODO 
    auxiliary_head_loss_decode_dict=dict(type='DiceLoss', use_sigmoid=False, loss_weight=0.4) # DiceLoss损失函数 # TODO 

    # 如果使用slide模式，则开启align_corners
    if test_cfg_mode == "slide":
        align_corners = True
        test_slide = 'testslide' # 算法名进行标记
    else:
        align_corners = False
        test_slide = 'no_testslide' # 算法名进行标记


    ########### 3.生成各个部分 ########### 
    _base_ = generate_base_config(alg_file_name=alg_file_name, dataset_file_name=dataset_file_name, schedule_file_name=schedule_file_name)
    norm_cfg = generate_norm_cfg(GPU_num=GPU_num)
    data_preprocessor = generate_data_preprocessor(crop_size = crop_size, mean = mean, std = std)

    pretrained = generate_model_pretrained(pretrained_pth = pretrained_pth)
    backbone = generate_model_backbone(depth=depth)
    model_data_preprocessor = data_preprocessor # 修改data_preprocessor
    model_data_preprocessor = generate_model_data_preprocessor(model_data_preprocessor=model_data_preprocessor)
    decode_head = generate_model_decode_head(num_classes=num_classes, decode_head_loss_decode_dict=decode_head_loss_decode_dict, align_corners=align_corners)
    auxiliary_head = generate_model_auxiliary_head(num_classes=num_classes, auxiliary_head_loss_decode_dict=auxiliary_head_loss_decode_dict, align_corners=align_corners)
    # 综合model
    model = dict(
        pretrained = pretrained,
        backbone = backbone,
        data_preprocessor = model_data_preprocessor,
        decode_head = decode_head,
        auxiliary_head = auxiliary_head,
    )

    test_cfg = generate_model_test_cfg(test_cfg_mode=test_cfg_mode, crop_size=crop_size, test_cfg_crop_div_stride=test_cfg_crop_div_stride)
    optim_wrapper = generate_optim_wrapper()
    param_scheduler = generate_param_scheduler(train_type, train_time_or_epoch_k)

    ########### 4.程序写入 ###########
    # 算法名称解析：danet【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}_r{depth}_{'Pre' if select_pretrained else 'NoPre'}_g{GPU_num}-{schedule_file_name.lstrip('schedule_')}_{dataset_file_name}-{crop_size[0]}x{crop_size[1]}-{test_slide}.py"
    output_configs_alg_my_alg = os.path.join(f'./configs/danet/', 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, test_cfg=test_cfg, optim_wrapper=optim_wrapper, param_scheduler=param_scheduler)

    # 将信息写入文件
    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)
