"""
LTESOM - Long Term Energy System Optimization Model 
Copyright (C) 2021, Peking University, College of Engineering (COE), 
Department of Industrial Engineering and Management
"""

### Working directory
cd(dirname(@__FILE__))

## Julia Enironment
using Pkg
env_path = "../env/julenv.jl"
# Run this line to activate the Julia virtual environment for GenX; 
# skip it, if the appropriate package versions are installed
#include(env_path) 
Pkg.activate("LTESOMEnv")
### Set relevant directory paths
src_path = "../src/"
settings_path = joinpath(pwd(), "Settings")
root_path = pwd()

### Load GenX and other modules
println("Loading packages")
push!(LOAD_PATH, src_path)

using GenX
using YAML

### Settings initialization
setup = Dict()
genx_settings = joinpath(settings_path, "genx_settings.yml")
setup_genx = YAML.load(open(genx_settings))
global_settings = joinpath(settings_path, "global_model_settings.yml")
setup_global = YAML.load(open(global_settings))
setup = merge(setup_genx, setup_global)

### Cluster time series inputs if necessary or specified by the user
TDRpath = joinpath(root_path, setup["TimeDomainReductionFolder"])
if setup["TimeDomainReduction"] == 1
    if (!isfile(TDRpath*"/Load_data.csv")) || (!isfile(TDRpath*"/Generators_variability.csv")) || (!isfile(TDRpath*"/Fuels_data.csv"))
        println("Clustering Time Series Data...")
        cluster_inputs(root_path, settings_path, setup)
    else
        println("Time Series Data Already Clustered.")
    end
end

### Configure solver
solver_settings_path = joinpath(settings_path, "solvers")
OPTIMIZER = configure_solver(setup["Solver"], solver_settings_path)

### Running a case
## Load inputs
inputs = load_inputs(setup, root_path)

## Generate model
EP = generate_model(setup, inputs, OPTIMIZER)

## Solve model
EP, solve_time = solve_model(EP, setup)
inputs["solve_time"] = solve_time # Store the model solve time in inputs

## Write power system output
out_path = "$root_path/Results"
out_path = write_outputs(EP, out_path, setup, inputs)

# Run MGA if the MGA flag is set to 1 else only save the least cost solution
# Only valid for power system analysis at this point
if setup["ModelingToGenerateAlternatives"] == 1
    mga(EP,root_path,setup,inputs,out_path)
end