#!/usr/bin/env bash
# This script is intended to be sourced, not executed directly.

_dayoa_activation_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P)

day_activate_args=()
no_auto_stage_test_data=false
for day_activate_arg in "$@"; do
    case "$day_activate_arg" in
        --no-auto-stage-test-data)
            no_auto_stage_test_data=true
            ;;
        *)
            day_activate_args+=("$day_activate_arg")
            ;;
    esac
done

if [[ "${#day_activate_args[@]}" -gt 3 ]]; then
    echo "ERROR: Too many day-activate arguments."
    return 64
fi

dayp="${day_activate_args[0]:-}"  # Profile code [local|slurm]
gbuild="${day_activate_args[1]:-}" # genome build code [hg38|b37]
remote_call="${day_activate_args[2]:-}" # remote call flag

echo "Requesting profile: $dayp"

if [[ -z "$dayp" ]]; then
    echo "ERROR: No profile specified, please specify [slurm|local] ([hg38|b37])"
    return 1
fi

if [[ "${DAY_BIOME:-}" == "MAC" && "$dayp" != "local" ]]; then
    echo "ERROR: macOS local mode only supports the local profile."
    return 3
fi

if [[ "$dayp" == "slurm" || "$dayp" == "slurm_rhel" ]]; then
    if [[ -z "${DYEC_CLUSTER_BUDGET_NAME:-}" ]]; then
        echo "ERROR: DYEC_CLUSTER_BUDGET_NAME is required for remote Slurm activation."
        return 3
    fi
fi

# Attempt to deactivate any existing environment
if [[ "${DAY_BIOME:-}" == "MAC" ]]; then
    echo "macOS local mode: using DAYOA while reinitializing DayOA."
else
    source bin/day_deactivate activate &> /dev/null
    echo "Attempting to deactivate existing environments and re-init with canonical cost context."
fi
dayoa_init_args=(--skip-cluster-budget-check)
if [[ -n "${DYEC_CLUSTER_BUDGET_NAME:-}" ]]; then
    dayoa_init_args+=(--cluster-budget-name "$DYEC_CLUSTER_BUDGET_NAME")
fi
if [[ -n "${DYEC_COST_CENTER_NAME:-}" ]]; then
    dayoa_init_args+=(--cost-center "$DYEC_COST_CENTER_NAME")
fi
source ./dyoainit "${dayoa_init_args[@]}"
dyoainit_ret_code=$?
if [[ "$dyoainit_ret_code" != "0" ]]; then
    echo "ERROR: source ./dyoainit with canonical cost context failed with return code $dyoainit_ret_code."
    return 4
fi
export DAY_PROFILE=$dayp

if [[ "$dayp" == "slurm" || "$dayp" == "slurm_rhel" ]]; then
    if ! PYTHONPATH="$_dayoa_activation_root${PYTHONPATH:+:$PYTHONPATH}" python3 -m daylily_omics_analysis.cost_context --execution slurm >/dev/null; then
        echo "ERROR: canonical DYEC cost context validation failed before Slurm activation."
        return 3
    fi
fi

if [[ "$no_auto_stage_test_data" == "true" ]]; then
    export DAYOA_NO_AUTO_STAGE_TEST_DATA=true
    echo "Configured DayOA to reject automatic profile test-data staging."
else
    unset DAYOA_NO_AUTO_STAGE_TEST_DATA
fi


# Check if DAY_ROOT is set
if [[ -z "$DAY_ROOT" ]]; then
    echo "ERROR: DAY_ROOT is not set. Have you executed 'source dyoainit'? Use -h for help."
    return 2
fi

# Handle help argument
if [[ "$dayp" =~ ^(-h|--help|help)$ ]]; then
    echo "Usage: day-activate [--no-auto-stage-test-data] [profile] [genome-build] [remote]"
    echo "This script activates a Daylily analysis profile."
    echo "Valid profiles are located in 'config/day_profiles/'."
    echo "Example: day-activate local"
    return 0
fi

export DAY_PROFILE_DIR="$DAY_ROOT/config/day_profiles/$DAY_PROFILE"
if [[ ! -d "$DAY_PROFILE_DIR" ]]; then
    colr "ERROR: Profile directory: $DAY_PROFILE_DIR does not exist." "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
    echo "Have you run 'day-activate'?"
    return 3
fi

if [[ "$remote_call" == "remote" ]]; then
    echo "Remote call detected. Activating conda hack"
    . "$HOME/miniconda3/etc/profile.d/conda.sh"
    export DAY_REMOTE_EXE="remote"
else
    unset DAY_REMOTE_EXE
fi

target_conda_env="DAYOA"

conda activate "$target_conda_env"
conda_ret_code=$?
if [[ "$conda_ret_code" != "0" ]]; then
    colr "ERROR: conda activate $target_conda_env failed with return code $conda_ret_code."  "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
    return 4
fi

source bin/util/profile_freshness_warn.bash
if [[ "$?" == "3" ]]; then
    colr "ERROR: source bin/util/profile_freshness_warn.bash"  "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
    return 4
fi

if ! which yq &>/dev/null; then
  echo "ERROR: yq is required in the active DAYOA environment."
  return 3
else
  echo "yq is already installed."
fi

if [[ "${DAY_BIOME:-}" == "MAC" ]]; then
    if [[ -z "${DAYOA_MAC_STATE_DIR:-}" ]]; then
        echo "ERROR: DAYOA_MAC_STATE_DIR is not set; rerun source dyoainit from DAY-EC."
        return 3
    fi
    export SENTIEON_TMPDIR="$DAYOA_MAC_STATE_DIR/sentieon_tmp"
    mkdir -p "$SENTIEON_TMPDIR" || return 3
    export TMPDIR="${DAYOA_RUNTIME_TMPDIR:-$SENTIEON_TMPDIR}"
    mkdir -p "$TMPDIR" || return 3
    export TMP="$TMPDIR"
    export TEMP="$TMPDIR"
    export SENTIEON_INSTALL_DIR=""
    CONFIG_FILE="${DAYLILY_CLI_GLOBAL_CONFIG:-$DAY_ROOT/config/daylily_cli_global.yaml}"
else
    CONFIG_FILE="${DAYLILY_CLI_GLOBAL_CONFIG:-$HOME/.config/daylily/daylily_cli_global.yaml}"
    git_tag=$(yq -r '.daylily.git_tag' "$CONFIG_FILE")
    export SENTIEON_TMPDIR=$(yq -r '.daylily.sentieon_tmpdir' "$CONFIG_FILE")
    export TMPDIR="${DAYOA_RUNTIME_TMPDIR:-$SENTIEON_TMPDIR}"
    mkdir -p "$TMPDIR" || return 3
    export TMP="$TMPDIR"
    export TEMP="$TMPDIR"
    export SENTIEON_INSTALL_DIR=$(yq -r '.daylily.sentieon_install_dir' "$CONFIG_FILE")
    export PATH="$PATH:$SENTIEON_INSTALL_DIR/bin/"

    if [[ ! -f ~/.config/daylily/$git_tag ]]; then
        echo ""
        echo "!!!!"
        echo "!!!!"
        echo "    WARNING: gittag:$git_tag not found touched in  ~/.config/daylily/$git_tag "
        echo "     This might be fine if you have cloned a more recent release of daylily compared to the tagged version used to create this ephemeral cluster."
        echo "     ... however, this is not expected. If you are running an ephemeral cluster headnode for days+, this is not the intended use of daylily, a fresh build might be called for."
        echo "     This is checked by testing if ~/.config/daylily/$git_tag exists ."
        echo "!!!!"
        sleep 3
    fi
fi

sentieon_endpoint_helper="$DAY_ROOT/bin/util/sentieon_license_endpoint.bash"
if [[ ! -f "$sentieon_endpoint_helper" ]]; then
    echo "ERROR: Sentieon endpoint helper not found: $sentieon_endpoint_helper"
    return 3
fi
source "$sentieon_endpoint_helper" || return 3
dayoa_resolve_sentieon_license_endpoint "$CONFIG_FILE" || return 3



# Verify profile exists
profile_info="$DAY_ROOT/config/day_profiles/$dayp/templates/profile.info"
if [[ -f "$profile_info" ]]; then
    # Extract environment variables from profile.info
    env_val=$(grep 'env_var_val' "$profile_info" | cut -d ':' -f 2)
    if [[ "$env_val" != "$DAY_PROFILE" ]]; then
        colr "ERROR: Profile '$dayp' does not match the expected environment variable value."  "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
        return 1
    fi
    env_script=$(grep 'env_script' "$profile_info" | cut -d ':' -f 2)
    mgps1val=$(grep 'terminal_abbreviation' "$profile_info" | cut -d ':' -f 2)

    # Source the environment script
    if [[ ! -f "$env_script" ]]; then
        echo "ERROR: Profile environment script not found: $env_script"
        return 1
    fi
    source "$env_script"
    pe_ret_code=$?
    export DYPS1="$mgps1val"
else
    colr "ERROR: Profile '$dayp' not found."  "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
    return 1
fi

# Check for 'colr' command
if ! command -v colr &> /dev/null; then
    echo "WARNING: 'colr' package is missing; using plain output." 1>&2
fi

# Check for errors during activation
if [[ "$pe_ret_code" != "0" ]]; then
    source bin/util/col_error.bash
    colr "ERROR: Activation failed with return code $pe_ret_code."  "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
    colr ""  "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
    colr  "Have you run 'day-build'? If so, try 'bin/day_deactivate reset; source dyoainit; day-activate local;'"  "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
    return $pe_ret_code
else


    gbuild_ret_code=0
    if [[ "$gbuild" != "" ]]; then
        source bin/day_set_genome_build $gbuild
        gbuild_ret_code=$?
    else
        colr "Skipping genome build activation."  "$DY_WI1" "$DY_IB2" "$DY_IS1" 1>&2
    fi

    if [[ "$gbuild_ret_code" != "0" ]]; then
        colr  "ERROR:  dy-g $gbuild ($gbuild_ret_code)  failed." "$DY_WT0" "$DY_WB0" "$DY_WS1" 1>&2
        return 5
    fi
    colr "       _______ GREAT SUCCESS _______       " "$DY_IT0" "$DY_IB0" "$DY_IS1"
    export PS1="$DYPS1$PS1"
fi

return 0
