#!/usr/bin/env python3

import pandas as pd
import sys
import os
import numpy as np
import random


# returns the value in the first column it finds that contains
#         the param name.  (for a given row
def getParam(param_name, row_indx, df_in):
    for index, row in df_in.iterrows():
        if (index == row_indx):
            for column_name, value in row.items():
                if (param_name in column_name):
                    return(float(value))
    print('ERROR: Could not find entry in df that contains' + str(param_name))
    return(0.0)



def main():
    if len(sys.argv) != 2:
        print("Usage: python process_mission.py param_cent.txt")
        sys.exit(1)

    filename = sys.argv[1]
    print(filename)

    param_dict = {}
    try:
        with open(filename, "r") as file:
            for line in file:
                if "=" in line:
                    param, value = line.strip().split("=", 1)
                    param_dict[param.strip()] = value.strip()
    except FileNotFoundError:
        print("Error: File '{filename}' not found.")

    print(param_dict)
    path = os.path.dirname(filename)

    count = 0
    perturb_pct = 0.8
    min_val = 0.0
    max_val = 300.0
    for param, value in param_dict.items():

        count += 1

        # generate a file + this value
        perturb_value = float(value) + random.random() * 10.0
        perturb_value = np.clip(perturb_value, min_val, max_val)
        perturb_value_str = "{:.3f}".format(perturb_value)

        newfilename = path + '/param' + str(count) + '.txt'
        
        # Open the file in write mode ('w')
        with open(newfilename, "w") as f:
            # Write the new file
            f.write(param + '=' + perturb_value_str + '\n')

            for static_param, static_value in param_dict.items():
                # skip it if this param is the one we are changing.
                if (param == static_param):
                    continue
                f.write(static_param + '=' + str(static_value) + '\n')

        # there must be a better way to do this. 
        count += 1

        # generate a file - this value
        perturb_value = float(value) - random.random() * 10.0
        perturb_value = np.clip(perturb_value, min_val, max_val)
        perturb_value_str = "{:.3f}".format(perturb_value)

        newfilename = path + '/param' + str(count) + '.txt'
        
        # Open the file in write mode ('w')
        with open(newfilename, "w") as f:
            # Write the new file
            f.write(param + '=' + perturb_value_str + '\n')

            for static_param, static_value in param_dict.items():
                # skip it if this param is the one we are changing.
                if (param == static_param):
                    continue
                f.write(static_param + '=' + str(static_value) + '\n')
        
        
    quit()

        
            
if __name__ == "__main__":
    main()
