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

dayp="$1"  # Profile code [loal|slurm]
gbuild="$2" # genome build code [hg38|b37]
remote_call="$3" # remote call flag

echo "Requesting profile: $dayp"
DP="${DAY_PROJECT:-global}"

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

# 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 & re-init with --project $DP ."
fi
source ./dyoainit --project "$DP" --skip-project-check &> /dev/null
dyoainit_ret_code=$?
if [[ "$dyoainit_ret_code" != "0" ]]; then
    echo "ERROR: source ./dyoainit --project $DP --skip-project-check failed with return code $dyoainit_ret_code."
    return 4
fi
export DAY_PROFILE=$dayp


# 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 [[ "$1" =~ ^(-h|--help|help)$ ]]; then
    echo "Usage: day-activate [profile]"
    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
  if [[ "${DAY_BIOME:-}" == "MAC" ]]; then
    echo "ERROR: yq is required in the DAY-EC environment for macOS local mode."
    return 3
  fi
  echo "yq not found. Installing via conda in base environment..."
  conda install -c conda-forge yq -y || {
    echo "Failed to install yq."
    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="$SENTIEON_TMPDIR"
    export SENTIEON_LICENSE_YAM=""
    export SENTIEON_INSTALL_DIR=""
    export SENTIEON_LICENSE=""
else
    CONFIG_FILE=~/.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=$SENTIEON_TMPDIR
    export SENTIEON_LICENSE_YAM=$(yq -r '.daylily.sentieon_lic_path' "$CONFIG_FILE")
    export SENTIEON_INSTALL_DIR=$(yq -r '.daylily.sentieon_install_dir' "$CONFIG_FILE")
    export PATH="$PATH:$SENTIEON_INSTALL_DIR/bin/"
    export SENTIEON_LICENSE=''

    if [[ ! -f "$SENTIEON_LICENSE_YAM" ]]; then
        echo "WARNING: sentieon lic file $SENTIEON_LICENSE_YAM not found."

        sentieon_license_dir="/fsx/references/runtime_assets/cached_envs"
        sentieon_detected_license=""
        sentieon_detected_count=0
        sentieon_longest_filename_len=-1
        if [[ -d "$sentieon_license_dir" ]]; then
            while IFS= read -r -d '' sentieon_candidate; do
                sentieon_detected_count=$((sentieon_detected_count + 1))
                sentieon_filename="$(basename "$sentieon_candidate")"
                if (( ${#sentieon_filename} > sentieon_longest_filename_len )); then
                    sentieon_longest_filename_len=${#sentieon_filename}
                    sentieon_detected_license="$sentieon_candidate"
                fi
            done < <(find "$sentieon_license_dir" -maxdepth 1 -type f -name '*.lic' -print0 | sort -z)
        fi

        if [[ "$sentieon_detected_count" -eq 1 ]]; then
            export SENTIEON_LICENSE="$sentieon_detected_license"
            echo "WARNING: SENTIEON_LICENSE was not configured with a valid file; auto assigning a detected Sentieon license: $SENTIEON_LICENSE"
        elif [[ "$sentieon_detected_count" -gt 1 ]]; then
            export SENTIEON_LICENSE="$sentieon_detected_license"
            echo "WARNING: SENTIEON_LICENSE was not configured with a valid file; found $sentieon_detected_count license files under $sentieon_license_dir."
            echo "WARNING: Auto assigning a detected Sentieon license with the longest filename: $SENTIEON_LICENSE"
        else
            echo "WARNING: sentieon lic file not detected in '$sentieon_license_dir/*.lic'."
            echo "If you try to use any of the sentieon tools, you will get an error."
        fi
    else
        echo "Using sentieon license file: $SENTIEON_LICENSE_YAM from ~/.config/daylily/daylily_cli_global.yaml"
        export SENTIEON_LICENSE=$SENTIEON_LICENSE_YAM
    fi

    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



# Verify profile exists
profile_info="$DAY_ROOT/config/day_profiles/$1/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 '$1' 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 '$1' 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
