#!/bin/bash

# RPG Workshop Setup Script for Linux/macOS
# This script sets up the conda environment and installs dependencies
#
# ============================================================================
# TERMS OF SERVICE NOTICE
# ============================================================================
# By running this script, you agree to the Anaconda Terms of Service:
# https://www.anaconda.com/terms-of-service
#
# This script will prompt you to accept the Anaconda TOS before proceeding.
# If you do not agree, please exit now (Ctrl+C).
# ============================================================================

set -euo pipefail

# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

echo "=== RPG Workshop Setup ==="
echo ""

REQ_FILE="$PROJECT_ROOT/requirements.txt"
if [ ! -f "$REQ_FILE" ]; then
    echo "Error: Missing requirements.txt at: $REQ_FILE"
    exit 1
fi

# Function to check if conda is available
ensure_conda_on_path() {
    if command -v conda >/dev/null 2>&1; then
        return 0
    fi
    if [ -f "$HOME/miniconda3/bin/conda" ]; then
        export PATH="$HOME/miniconda3/bin:$PATH"
        return 0
    fi
    if [ -f "$HOME/anaconda3/bin/conda" ]; then
        export PATH="$HOME/anaconda3/bin:$PATH"
        return 0
    fi
    return 1
}

calc_sha256() {
    if command -v sha256sum >/dev/null 2>&1; then
        sha256sum "$1" | awk '{print $1}'
    elif command -v shasum >/dev/null 2>&1; then
        shasum -a 256 "$1" | awk '{print $1}'
    elif command -v openssl >/dev/null 2>&1; then
        # outputs: SHA256(filename)= <hash>
        openssl dgst -sha256 "$1" | awk '{print $NF}'
    else
        echo "Error: No SHA-256 tool found (sha256sum, shasum, or openssl)."
        return 2
    fi
}

verify_sha256() {
    local file_path="$1"
    local expected_hash="$2"
    local actual_hash="$(calc_sha256 "$file_path")"
    if [ "$actual_hash" != "$expected_hash" ]; then
        echo "Error: SHA-256 mismatch for $file_path"
        echo "Expected: $expected_hash"
        echo "Actual:   $actual_hash"
        echo "Deleting corrupted file."
        rm -f "$file_path"
        return 1
    fi
    echo "Checksum verified for $file_path"
    return 0
}

# Function to install Miniconda
install_miniconda() {
    echo "Conda not found. Installing Miniconda..."

    # Detect OS and architecture
    OS="$(uname -s)"
    ARCH="$(uname -m)"

    case "$OS" in
    Linux)
        case "$ARCH" in
        x86_64)
            MINICONDA_URL="https://repo.anaconda.com/miniconda/Miniconda3-py313_25.7.0-2-Linux-x86_64.sh"
            SHA256_HASH="dda3629462ba1cfa72eb74535214c2e315c77f1cfb0f02046537e99f1bf64abc"
            ;;
        aarch64|arm64)
            MINICONDA_URL="https://repo.anaconda.com/miniconda/Miniconda3-py313_25.7.0-2-Linux-aarch64.sh"
            SHA256_HASH="350dc95067e0c87bcaa67367e60ea1caae01872adeb945c760bb4a67518d9673"
            ;;
        *)
            echo "Error: Unsupported Linux architecture: $ARCH"
            exit 1
            ;;
        esac
        ;;
    Darwin)
        if [ "$ARCH" = "arm64" ]; then
        MINICONDA_URL="https://repo.anaconda.com/miniconda/Miniconda3-py313_25.7.0-2-MacOSX-arm64.sh"
        SHA256_HASH="5c0137ef38c153649da28ca31a420b9c12c94cf636319beb8c925396d797fe62"
        else
        MINICONDA_URL="https://repo.anaconda.com/miniconda/Miniconda3-py313_25.7.0-2-MacOSX-x86_64.sh"
        SHA256_HASH="9c88674b1a839eeb4cff006df397a05ea7d896472318fd84b7070278f9653dc6"
        fi
        ;;
    *)
        echo "Error: Unsupported operating system: $OS"
        exit 1
        ;;
    esac

    INSTALLER="$(mktemp "${TMPDIR:-/tmp}/miniconda_installer.XXXXXX.sh")"

    echo "Downloading Miniconda from $MINICONDA_URL..."
    if command -v curl &> /dev/null; then
        curl -fsSL "$MINICONDA_URL" -o "$INSTALLER"
    elif command -v wget &> /dev/null; then
        wget -q "$MINICONDA_URL" -O "$INSTALLER"
    else
        echo "Error: Neither curl nor wget found. Please install one of them."
        exit 1
    fi

    verify_sha256 "$INSTALLER" "$SHA256_HASH"

    echo "Installing Miniconda to: $HOME/miniconda3"
    bash "$INSTALLER" -b -p "$HOME/miniconda3"
    rm -f "$INSTALLER"

    export PATH="$HOME/miniconda3/bin:$PATH"

    echo "Miniconda installed successfully!"
    echo ""
}

accept_conda_tos() {
    echo "This script will accept Anaconda's Terms of Service on your behalf."
    echo "Review the TOS at: https://www.anaconda.com/terms-of-service"
    echo ""

    echo "Installing conda-anaconda-tos (if needed)..."
    conda list -n base conda-anaconda-tos >/dev/null 2>&1 || \
        conda install -n base -y conda-anaconda-tos

    conda tos accept
    echo "TOS accepted."
    echo ""
}

base_default() {
    read -r -p "Do you want base to be activated for new terminals by default? (Y/N): " confirmation
    case "$confirmation" in
    Y|y) 
        conda config --set auto_activate true
        echo ""
        echo "Setting base to be activated for new terminals by default..."
        echo "if you changed your mind, you can run 'conda config --set auto_activate false' later."
        echo "The command 'conda deactivate' can be used to exit the base environment."
        ;;
    *)
        conda config --set auto_activate false
        echo ""
        echo "if you changed your mind, you can run 'conda config --set auto_activate true' later."
        echo "The command 'conda deactivate' can be used to exit the base environment."
        ;;
    
    esac
}

# Main script
echo "Checking for conda installation..."

if ! ensure_conda_on_path; then
    install_miniconda
fi

echo "Conda found: $(conda --version)"
echo ""

# === ACCEPTS ANACONDA TERMS OF SERVICE ===
# The following section accepts Anaconda's Terms of Service for this user.
# TOS: https://www.anaconda.com/terms-of-service
accept_conda_tos

# Setup if conda base should run for new terminals by default
base_default

# Check if environment already exists
ENV_NAME="RPG_Workshop1"
OS="$(uname -s)"
ARCH="$(uname -m)"



if conda env list | awk 'NF && $1 !~ /^#/ {print $1}' | grep -qx "$ENV_NAME"; then
    echo "Environment '$ENV_NAME' already exists."
else
    echo "Creating conda environment '$ENV_NAME' with Python 3.12..."
    if [ "$OS" = "Darwin" ]; then
        # For macOS, use the conda-forge channel for better compatibility
        conda create -n "$ENV_NAME" python=3.11 -y
    else
        conda create -n "$ENV_NAME" python=3.12 -y
    fi
    echo "Environment created successfully!"
fi

echo ""
echo "Running environment '$ENV_NAME'..."
echo ""
echo "Installing requirements from requirements.txt..."
if [ "$OS" = "Darwin" ]; then
    if [ "$ARCH" = "arm64" ]; then
        conda run -n "$ENV_NAME" conda install --file "$PROJECT_ROOT/mac-requirements.txt" -y
    else
        conda run -n "$ENV_NAME" python -m pip install -r "$PROJECT_ROOT/requirements.txt"
    fi
else
    conda run -n "$ENV_NAME" python -m pip install -r "$PROJECT_ROOT/requirements.txt"
fi

echo ""
echo "=== Setup Complete! ==="
echo ""
echo "Environment '$ENV_NAME' is now active."
echo "To activate this environment in the future, run:"
echo "    conda activate $ENV_NAME"
echo ""
