#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Batch run worker for ML models. Reads in
settings csv from output-scratch. Used in conjunction with cloud computing


"""
import os
import sys
import configparser
import pandas as pd
import src.mlfcast as mlfcast

config = configparser.ConfigParser()
config.optionxform = str
config.read("config.ini")


def batch_worker_entry_point(row_index, output_dir):
    file_path = os.path.join(
        config["data"]["outputscratch"],
        config["tf_vs_ML"]["specFileStem"] + "_specifications.csv",
    )
    arg_combination = pd.read_csv(file_path)
    arg_combination = [tuple(x) for x in arg_combination.values]
    try:
        results = mlfcast.run_individual_ML_spec(arg_combination)
        outPath = os.path.join(
            output_dir,
            config["tf_vs_ML"]["specFileStem"] + "_run_" + str(row_index) + ".csv",
        )
        results.to_csv(outPath)
    except RuntimeError:
        error_message = "Run failed"
        outPath = os.path.join(
            output_dir,
            config["tf_vs_ML"]["specFileStem"] + "_failrun_" + str(row_index) + ".csv",
        )
        results = pd.DataFrame(arg_combination[row_index])
        results.to_csv(outPath)


if __name__ == "__main__":
    # SETTINGS AS PASSED BY BATCH
    line_of_file = int(sys.argv[1])
    output_dir = sys.argv[2]
    # Run the line_of_fileth entry
    batch_worker_entry_point(line_of_file, output_dir)
