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

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 = 'bisenetv1_r18-d32'
    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), (1024, 1024)]) # 选择切割大小
    data_preprocessor = generate_data_preprocessor(crop_size = crop_size, mean = mean, std = std)

    ########### 3.3. 生成model部分 ########### 
    model_data_preprocessor = data_preprocessor # 修改data_preprocessor
    # 获取backbone模型、是否需要预训练
    model_list = ['openmmlab/resnet18_v1c', 'openmmlab/resnet50_v1c', 'openmmlab/resnet101_v1c'] 
    selected_model_name, select_pretrained, pretrained_pth, selected_model_info = select_pretrained_model(model_list=model_list, need_select_pretrained = True) # 需要选择是否用预训练模型
    depth = selected_model_info['depth']
    
    if select_pretrained == True:
        pretrained_txt = 'Pre'
    else:
        pretrained_txt = 'NoPre'

    # 模型信息
    if selected_model_name == 'openmmlab/resnet18_v1c' :
        backbone_context_channels = (128, 256, 512)
        backbone_spatial_channels = (64, 64, 64, 128)
        backbone_out_channels = 256
        decode_head_in_channels = 256
        decode_head_channels = 256
        auxiliary_head_in_channels = 128
        auxiliary_head_channels = 64

    elif selected_model_name == 'openmmlab/resnet50_v1c' or selected_model_name == 'openmmlab/resnet101_v1c' :
        backbone_context_channels = (512, 1024, 2048)
        backbone_spatial_channels = (256, 256, 256, 512)
        backbone_out_channels = 1024
        decode_head_in_channels = 1024
        decode_head_channels = 1024
        auxiliary_head_in_channels = 512
        auxiliary_head_channels = 256
    
    # 需要选择预训练模型
    if select_pretrained == True:
        backbone_backbone_cfg = create_dict_by_kwargs(type='ResNet', norm_cfg=norm_cfg, depth=depth, init_cfg=dict(type='Pretrained', checkpoint=pretrained_pth))
    else:
        backbone_backbone_cfg = create_dict_by_kwargs(type='ResNet', norm_cfg=norm_cfg, depth=depth)

    backbone = create_dict_by_kwargs(context_channels=backbone_context_channels, norm_cfg=norm_cfg, spatial_channels=backbone_spatial_channels, out_channels=backbone_out_channels, backbone_cfg=backbone_backbone_cfg)
    
    # decode、auxiliary损失下载方式 TODO
    decode_head_loss_decode_dict=dict(type='DiceLoss', use_sigmoid=False, loss_weight=1.0) # decode损失函数 # TODO 
    decode_head = create_dict_by_kwargs(type='FCNHead',in_channels=decode_head_in_channels, channels=decode_head_channels, num_classes=num_classes)

    # auxiliary损失下载方式 TODO # 可更改
    # auxiliary_head_loss_decode_dict = dict(type='DiceLoss', use_sigmoid=False, loss_weight=0.4) # DiceLoss损失函数 # TODO # 可更改 
    auxiliary_head_loss_decode_dict = dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)
    auxiliary_head = [create_dict_by_kwargs(type='FCNHead', norm_cfg=norm_cfg, in_channels=auxiliary_head_in_channels, channels=auxiliary_head_channels, num_classes=num_classes, align_corners=False, loss_decode=auxiliary_head_loss_decode_dict),
                      create_dict_by_kwargs(type='FCNHead', norm_cfg=norm_cfg, in_channels=auxiliary_head_in_channels, channels=auxiliary_head_channels, num_classes=num_classes, align_corners=False, loss_decode=auxiliary_head_loss_decode_dict)]
    # 获取原始auxiliary_head
    auxiliary_head = get_var_from_py_file(alg_file_pth, var_name="model")["auxiliary_head"]
    # 新的auxiliary_head
    auxiliary_head_new = [create_dict_by_kwargs(type='FCNHead', norm_cfg=norm_cfg, in_channels=auxiliary_head_in_channels, channels=auxiliary_head_channels, num_classes=num_classes, align_corners=False, loss_decode=auxiliary_head_loss_decode_dict),
                      create_dict_by_kwargs(type='FCNHead', norm_cfg=norm_cfg, in_channels=auxiliary_head_in_channels, channels=auxiliary_head_channels, num_classes=num_classes, align_corners=False, loss_decode=auxiliary_head_loss_decode_dict)]
    # 更新auxiliary_head
    auxiliary_head = update_list_dict_var(auxiliary_head, auxiliary_head_new)

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

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

    ########### 4.程序写入 ###########
    # 算法名称解析：bisenetv1【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]}.py"
    output_configs_alg_my_alg = os.path.join(f'./configs/bisenetv1/', 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)

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