#!/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 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 create_empty_file(filename):
    try:
        with open(filename, 'w') as file:
            pass  # The file is created but remains empty
        print(f"Empty file '{filename}' created successfully.")
    except Exception as e:
        print(f"An error occurred: {e}")


def add_begin_to_namecouple(nfields,runtime):
    lines_to_append = """# =================================================================================================
# General OASIS configuration
# =================================================================================================
 $NFIELDS
    {nfields}
 $END
# -------------------------------------------------------------------------------------------------
 $RUNTIME
    {runtime}
 $END
# -------------------------------------------------------------------------------------------------
 $NLOGPRT
 0 0
 $END
# -------------------------------------------------------------------------------------------------
 $STRINGS 
# =================================================================================================
# Fields send from AMIP to IFS
# =================================================================================================
# --- AMIP forcing data --- [ifs amip]"""
    
    return(lines_to_append.format(nfields=nfields,runtime=runtime))


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

    return lines_to_append


if __name__ == '__main__':
    
    parser=argparse.ArgumentParser()
    parser.add_argument("--conf",type=str)
    parser.add_argument("--output",type=str)
    args = parser.parse_args()
    yaml_conf_file = args.conf
    output_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)

    # Creating the namcouple file amd insert the read-in data from YAML file 
    create_empty_file(output_file)
    lines=add_begin_to_namecouple(number_of_fields,RunLengthSec)
    append_multiple_lines_to_file(output_file, lines)
    
    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(output_file, lines)

    lines = add_end_to_namecouple()
    append_multiple_lines_to_file(output_file, lines)