library(h2o)
library(dataiku)

localH2O <- h2o.init(nthreads = -1)

# Load h2o model
h20_model <- dkuManagedFolderPath("c1YRtnGl")
top.level <- dir(h20_model)
model.path = paste(h20_model, top.level, sep="/")
h2o.model <- h2o.loadModel(model.path)
print(h2o.model)

# Recipe inputs
df <- dkuReadDataset("test")

#-----------------------------------------------------------------
# Settings
#-----------------------------------------------------------------
target.variable <- 'Churn'

features.num <- c(
    'Account_Length', 'VMail_Message', 'Day_Mins', 'Day_Calls', 'Day_Charge', 'Eve_Mins', 
    'Eve_Calls', 'Eve_Charge', 'Night_Mins', 'Night_Calls', 'Night_Charge', 'Intl_Mins', 
    'Intl_Calls', 'Intl_Charge', 'CustServ_Calls'        
)

features.cat <- c(
    'State', 'Area_Code', 'Intl_Plan', 'VMail_Plan'
)

#-----------------------------------------------------------------
# Preprocessing
#-----------------------------------------------------------------
df[features.cat]    <- lapply(df[features.cat], as.factor)
df[features.num]    <- lapply(df[features.num], as.double)
df[target.variable] <- lapply(df[target.variable], as.factor)
test.ml <- df[c(features.cat, features.num, target.variable)]

#-----------------------------------------------------------------
# Predictions
#-----------------------------------------------------------------
h2o.test <- as.h2o(test.ml, destination_frame = 'h2otest')
preds <- h2o.predict(h2o.model, h2o.test)
predictions <- as.data.frame(preds)
results <- cbind(df, predictions)

# Recipe outputs
dkuWriteDataset(results,"test_scored_h2o")
h2o.shutdown(prompt = FALSE)
