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

import sys
import warnings
from datetime import datetime
from pathlib import Path

import pandas as pd

import tripleblind as tb


# Suppress the SkLearn "UndefinedMetricWarning"
warnings.filterwarnings("ignore")

tb.util.set_script_dir_current()
data_dir = Path("example_data")

##########################################################################
# GET AUTHENTICATION TOKENS AND ESTABLISH CONNECTION TO THE ROUTER
#
tb.initialize(api_token=tb.config.example_user2["token"])

# Look for a model Asset ID from a previous run of 2_model_train.py
try:
    with open("asset_id.out", "r") as f:
        asset_id = f.readline().strip()
except:
    print("You must first run 2_model_train.py.")
    sys.exit(1)

recommender_model = tb.Asset(asset_id)

# Define a job using this model
job = tb.create_job(
    job_name="Recommender Inference - " + str(datetime.now()),
    operation=recommender_model,
    dataset=[data_dir / "ratings_test.csv"],
    params={"user_id_column": "userId", "top_n": 10},
)
if not job:
    print("ERROR: Failed to create the job -- do you have an Agreement to run this?")
    print()
    print(
        f"NOTE: Remote inference requires the user '{tb.config.example_user1['login']}' create an"
    )
    print(
        f"      Agreement on their algorithm asset with user '{tb.config.example_user2['login']}'"
    )
    print(
        f"      ({tb.config.example_user2['name']}) before they can use it to infer.  You can do"
    )
    print(f"      this on the Router at:")
    print(f"      {tb.config.gui_url}/dashboard/algorithm/{recommender_model.uuid}")
    sys.exit(1)
    # Run against the local test dataset
if job.submit():
    job.wait_for_completion()

    if job.success:
        filename = job.result.asset.retrieve(
            save_as="recommender_remote_predictions.zip", overwrite=True
        )
        pack = tb.Package.load(filename)
        result = pd.read_csv(pack.record_data_as_file())
        print("\nInference results:")
        print("    ", result)
    else:
        print(f"Inference failed")
