#!/usr/bin/env python3
# Copyright 2023 - Barcelona Supercomputing Center
# Authors: Amirpasha Mozaffari
# MIT License

import yaml
from yaml.loader import SafeLoader
import os 
import argparse
import sys 
from YAMLlUtils import read_yaml_conf_type1
import f90nml

# It will readin the YAML file that is generated by the RunExample and generate a namcouple list before 



def replace_string_in_file(input_file_path, target_string, new_string, output_file_path):
    with open(input_file_path, 'r') as input_file:
        content = input_file.read()

    updated_content = content.replace(target_string, new_string)

    with open(output_file_path, 'w') as output_file:
        output_file.write(updated_content)



def replace_strings_in_file(input_file_path, replacements_dict, output_file_path):
    with open(input_file_path, 'r') as input_file:
        content = input_file.read()

    for target_string, new_string in replacements_dict.items():
        content = content.replace(target_string, new_string)

    with open(output_file_path, 'w') as output_file:
        output_file.write(content)

def append_multiple_lines_to_file(file_path, lines_to_append):
    with open(file_path, 'a') as file:
       # for line in lines_to_append:
        file.write(lines_to_append + '\n')


def add_field_to_namcouple(send_id, receive_id, timestepsec,send_grid_name, receive_grid):
    lines_to_append =   str(send_id) + " " + str(receive_id) + " 1 " + str(timestepsec) + " 1 rstas.nc EXPOUT \n" + \
                        str(send_grid_name) + " " + str(receive_grid) + " LAG=0 \n" + \
                        "P  0  P  0\n" + \
                        "SCRIPR \n" + \
                        "GAUSWGT LR SCALAR LATITUDE 1 9 2.0"

    return lines_to_append    



# def get_values_as_string(data_dict):
#     if not isinstance(data_dict, dict):
#         raise ValueError("Input must be a dictionary.")

#     send_id_values = data_dict.get('send_id', [])
#     if not isinstance(send_id_values, list):
#         raise ValueError("The value associated with 'send_id' key must be a list.")
#     return ":".join(str(value) for value in send_id_values)


# def add_field_to_namcouple_single_para(keys_string, values_string, timestepsec,send_grid_name, receive_grid):
#     lines_to_append =   str(keys_string) + " " + str(values_string) + " 1 " + str(timestepsec) + " 1 rstas.nc EXPOUT \n" + \
#                         str(send_grid_name) + " " + str(receive_grid) + " LAG=0 \n" + \
#                         "P  0  P  0\n" + \
#                         "SCRIPR \n" + \
#                         "GAUSWGT LR SCALAR LATITUDE 1 9 2.0"
#     return lines_to_append 



def add_end_to_namecouple():
    lines_to_append = "# -------------------------------------------------------------------------------------------------\n" + \
                      "$END\n" + \
                      "# =================================================================================================\n" 

    return lines_to_append


def text_to_f90nml(input_file, output_file):
    with open(input_file, 'r') as infile:
        lines = infile.readlines()

    data = {}
    for line in lines:
        key, value = line.strip().split()
        data[key] = value

    nml_data = f90nml.Namelist(data)
    nml_data.write(output_file)



# def yaml_to_f90nml(yaml_file, f90nml_file):
#     # Read YAML file
#     with open(yaml_file, 'r') as file:
#         data = yaml.safe_load(file)

    # # Write to Fortran namelist file
    # with open(f90nml_file, 'w') as file:
    #     nml = f90nml.Namelist(data)
    #     nml.write(file)


if __name__ == '__main__':
    # receive the yaml experiment input file is it exists , otherwise pass 
    
    parser=argparse.ArgumentParser()
    parser.add_argument("--conf",type=str)
    parser.add_argument("--input",type=str)
    parser.add_argument("--output",type=str)
    args = parser.parse_args()
    yaml_conf_file = args.conf
    input_file_path = args.input
    intermediate_file =  args.output 

    ModelNameSend, ModelNameReceive, LogFileName, PartitionType, RunLengthSec, TimeStepSec, StartYear, StartMonth,   \
    StartDay, FixYear, GridInfo, LDebug, fileIn_vars_config, oasisOut_vars_config, OasisOutputVars_readin = read_yaml_conf_type1(yaml_conf_file)

    number_of_fields = len(OasisOutputVars_readin)

    replacements_dict = {
                "(nfileds)": str(number_of_fields),
                "(runtime)": str(RunLengthSec),    
                }
    
    replace_strings_in_file(input_file_path, replacements_dict, intermediate_file)

    for v in OasisOutputVars_readin.keys() :

        lines = add_field_to_namcouple(OasisOutputVars_readin[v]['send_id'], OasisOutputVars_readin[v]['receive_id'], \
                                    TimeStepSec,OasisOutputVars_readin[v]['send_grid_name'], OasisOutputVars_readin[v]['receive_grid_name'])
        
        append_multiple_lines_to_file(intermediate_file, lines)
    

    lines = add_end_to_namecouple()
    append_multiple_lines_to_file(intermediate_file, lines)