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

print(
    """The XGBoost library produces models which can be tricky to run locally
due to dependencies on other libraries which may not be easily installed on some
hardware and operating system combinations, e.g. MacOS on Apple M1/M2
processors. This script demonstrates how to load a trained XGBoost model
decoupled from the TripleBlind ecosystem and may work unaltered if the
necessary dependencies are available, but some customization maybe be
required to run on some systems.
"""
)

# Remove the following line to run this script.
raise SystemExit("This script is for reference only.")

from pathlib import Path

import numpy as np
import pandas as pd

import tripleblind as tb


try:
    import xgboost
except Exception as e:
    print(f"Exception: {e}")  # Show raw error

    import platform

    from colorama import Fore, Style

    if platform.processor() == "arm":
        tb.util.wrap(
            "\nLocal xgboost inference requires a library which doesn't yet run on "
            + "ARM-based machines, such as the Apple M1/M2 processors. "
            + "XGBoost models can still be trained and used for inference via "
            + "TripleBlind, see the 3b_ and 3c_ script examples."
        )
    else:
        tb.util.wrap(
            Fore.RED + "\nDependency missing: XGBoost requires libomp" + Style.RESET_ALL
        )
        print()
        tb.util.wrap(
            "Local xgboost inference requires an additional library "
            + "install. On MacOS xgboost requires libomp 11 which is not "
            + "available from brew. Run the following commands to get the "
            + "correct version:"
        )
        print(
            Fore.CYAN + "  mamba install conda-forge::llvm-openmp=11" + Style.RESET_ALL
        )
        print()
        tb.util.wrap("Then update your dylib reference so xgboost can find it:")
        print(
            Fore.CYAN
            + "  cp ~/anaconda3/envs/tripleblind/lib/libomp.dylib /usr/local/bin/libomp.dylib"
            + Style.RESET_ALL
        )
    raise SystemExit(1)


def load_xgmodel():
    pack = tb.Package.load(data_dir / "xgboost_sant_model.zip")
    model = pack.model()
    return model


tb.util.set_script_dir_current()
data_dir = Path("example_data")
data_dir.mkdir(exist_ok=True)

# Retrieve a test dataset for "batch" testing
#
data_file = tb.util.download_tripleblind_resource(
    "test.csv",
    save_to_dir=data_dir,
    cache_dir="../../.cache",
)

model = load_xgmodel()
print(model)

# Load and split test data into independent X (data) and y (target) dataframes
data_X = pd.read_csv(data_file, header=0)
data_y = data_X["target"].copy()
del data_X["target"]

X = data_X.values
y = np.expand_dims(data_y.values, axis=1)

predictions = model.predict(X)
actual = y.to_numpy() if isinstance(y, pd.DataFrame) else y.flatten()
accuracy = np.sum(actual == predictions) / len(actual)
print(f"Predictions: {predictions}")
print(f"Actual:      {actual}")
print(f"Accuracy:    {accuracy*100}%")
