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

import sys
from datetime import datetime

import tripleblind as tb


tb.util.set_script_dir_current()
# Unique value used by all scripts in this folder.  Edit "run_id.txt" to change
run_id = tb.util.read_run_id()


##########################################################################
# GET AUTHENTICATION TOKENS AND ESTABLISH CONNECTION TO THE ROUTER
#
# Establish the connection details to reach the TripleBlind instance.
# Unless explicitly specified, all operations will occur via this default
# session as the user 'organization_one'.
tb.initialize(api_token=tb.config.example_user1["token"])


# Find the training databases in the Router index
dataset_train0 = tb.Asset.find(
    f"train-ssd-{run_id}", owned_by=tb.config.example_user2["team_id"]
)
dataset_train1 = tb.Asset.find(
    f"train1-ssd-{run_id}", owned_by=tb.config.example_user3["team_id"]
)
if not dataset_train0 or not dataset_train1:
    print("Datasets not found.")
    print("You must run 1_position_data_on_accesspoint.py first")
    sys.exit(1)


# Loss function names must be consistent with PyTorch.
#   See: https://pytorch.org/docs/stable/nn.html#loss-functions
# Currently tested: 'BCEWithLogitsLoss', 'NLLLoss', 'CrossEntropyLoss'
loss_name = "CrossEntropyLoss"

# Optimizer names must be consistent with PyTorch.
#   See: https://pytorch.org/docs/stable/optim.html
# Currently tested: 'SGD', 'Adam', 'Adadelta'
optimizer_name = "Adam"
optimizer_params = {"lr": 0.001}

roi_pre = tb.ROIPreprocessor.builder().target_path_column("label_path")
# train the network
job = tb.create_job(
    job_name=f"SSD - {str(datetime.now()).replace(' ', ' @ ')}",
    operation=tb.Operation.REGION_OF_INTEREST_TRAIN,
    dataset=[dataset_train0, dataset_train1],
    preprocessor=roi_pre,
    params={
        "epochs": 2,
        "test_size": 0.01,
        "batchsize": 4,
        "n_classes": 20,  # include the total number of classes WITHOUT counting the background
        "loss_meta": {"name": loss_name},
        "optimizer_meta": {"name": optimizer_name, "params": optimizer_params},
        "data_type": "table",
        "data_shape": [
            300,  # image data: width
            300,  #             height
            3,  #              color bytes.  1 == grayscale
        ],
        # "model_output": "multiclass",  # binary/multiclass/regression
    },
)


print("Training network...")
if job.submit():
    job.wait_for_completion()

    if job.success:
        print()
        print("Trained Network Asset ID:")
        print("    ===============================================")
        print(f"    ===>  {job.result.asset.uuid} <===")
        print("    ===============================================")
        print("    Algorithm: Deep Learning Model")
        print(f"    Job ID:    {job.job_name}")
        print()

        # Save for use in 3b_fed_inference.py
        with open("asset_id.out", "w") as output:
            output.write(str(job.result.asset.uuid))

        trained_network = job.result.asset
    else:
        print(f"Training failed")
        sys.exit(1)

    # Pull down the model for local validation
    local_filename = trained_network.retrieve(save_as="local.zip", overwrite=True)
    print("Trained network has been downloaded as:")
    print(f"   {local_filename}")

    # Save for use in 3a_local_inference.py
    with open("local_model_filename.out", "w") as output:
        output.write(str(local_filename))

    # Save for use in 3b_fed_inference.py / 3c_smpc_inference.py
    with open("model_asset_id.out", "w") as output:
        output.write(str(job.result.asset.uuid))

    print("Ready to run local inference.")
    print()

    # Create an agreement which allows the other team to use this
    # trained model in subsequent steps.
    agreement = job.result.asset.add_agreement(
        with_team=tb.config.example_user2["team_id"], operation=tb.Operation.EXECUTE
    )
    if agreement:
        print("Created Agreement for use of trained Asset.")
