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

import warnings

import pandas as pd

import tripleblind as tb


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


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

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

alg = tb.Asset(asset_id)

df = pd.read_csv("movie_ratings.csv")
test_df = df[40:50]

comments = test_df["comments"]
comments.to_csv("movie_rating_test.csv", index=False, header=True)

# Define a job using this model
job = tb.create_job(
    job_name=f"BERT Inference - {tb.util.timestamp()}",
    operation=alg,
    dataset="movie_rating_test.csv",
    params={},
)
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/{alg.uuid}")
    raise SystemExit(1)

# Run against the local test dataset
if job.submit():
    job.wait_for_completion()

    if job.success:
        job.result.asset.retrieve(
            save_as="sentiment_remote_predictions.zip", overwrite=True
        )

        print("\nInference results:")
        print("    ", job.result.dataframe)
    else:
        print(f"Inference failed")
