#!/usr/bin/env Rscript
# Copyright (c) TripleBlind Holdings, Inc. Confidential and Proprietary. All rights reserved.

# Install required packages if not already installed
RequiredPackages <- c("reticulate", "stringr")
for (i in RequiredPackages) { # Installs packages if not yet installed
  if (!require(i, character.only = TRUE)) install.packages(i)
}

# Load packages
library(reticulate)
library(stringr)

tb <- import("tripleblind")

tb$util$set_script_dir_current()
tb$initialize(api_token <- tb$config$example_user1[["token"]])

result <- tryCatch(
  {
    run_id <- tb$util$read_run_id()
    bank1 <- tb$TableAsset$find(paste("JPM Customers-", run_id, sep = ""))
    bank2 <- tb$TableAsset$find(paste("PNB Customers-", run_id, sep = ""))
    broker <- tb$TableAsset$find(paste("Broker licenses-", run_id, sep = ""))
  },
  error = function(err) {
    print(paste("An error occurred: ", err, ""))
    print("You must run 1_position_data_on_accesspoint.py.")
    quit(save = "ask")
  }
) # end trycatch

overlap <- broker$intersect(
  intersect_with = list(bank1, bank2),
  match_column = "ssn",
  silent = TRUE
)

if (!is.null(overlap)) {
  print(paste("Overlap Asset ID: ", overlap$uuid, sep = ""))
  cat("\n")
  print("Overlap values saved to file:")
  print(paste("    ", overlap$download(save_as = "out.csv", overwrite = TRUE), sep = ""))
} else {
  print("Overlap failed")
  quit(save = "ask")
}
