#!/usr/bin/env bash

# dyinit: Initialize the Daylily environment
# This script must be sourced, not executed directly.

# Ensure the script is sourced
if [[ "${BASH_SOURCE[0]:-}" == "${0:-}" ]]; then
    echo "Error: This script must be sourced, not executed directly."
    echo "Usage: source $0 [--cluster-budget-name <cluster>] [--cost-center <cost_center>]"
    echo "       [--project <cluster>] [--skip-cluster-budget-check|--strict-cluster-budget-check]"
    exit 3
fi

region=""
canonical_budget_env="${DYEC_CLUSTER_BUDGET_NAME:-}"
canonical_cost_center_env="${DYEC_COST_CENTER_NAME:-}"
legacy_day_project_env="${DAY_PROJECT:-}"
legacy_daylily_cost_center_env="${DAYLILY_COST_CENTER:-}"
cluster_budget_arg=""
cost_center_arg=""
legacy_project_arg=""
DAYOA_PLATFORM="$(uname -s 2>/dev/null || echo unknown)"
DAYOA_MAC_LOCAL=false
if [[ "$DAYOA_PLATFORM" == "Darwin" ]]; then
    DAYOA_MAC_LOCAL=true
fi

# Set default contact email if not already set
export DAY_CONTACT_EMAIL="${DAY_CONTACT_EMAIL:-john@daylilyinformatics.com}"

# Source AWS ParallelCluster configuration to get the region
if [[ -f "/etc/parallelcluster/cfnconfig" ]]; then
    source "/etc/parallelcluster/cfnconfig"
    region="${cfn_region:-}"
elif [[ "$DAYOA_MAC_LOCAL" == true ]]; then
    region="local-mac"
else
    echo "Error: AWS ParallelCluster config not found at /etc/parallelcluster/cfnconfig"
fi

# Check if region is set
if [[ -z "$region" ]]; then
    echo "Error: cfn_region is not set or is empty."
    return 3
fi

# Function to display usage
usage() {
    echo "This script initializes the Day CLI (commands aliased to dy-* )."
    echo "Region is autodetected as $region"
    echo "Usage: source $0 [--cluster-budget-name <cluster>] [--cost-center <cost_center>]"
    echo "       [--project <cluster>] [--skip-cluster-budget-check|--strict-cluster-budget-check]"
    echo "A remote headnode requires --cluster-budget-name or DYEC_CLUSTER_BUDGET_NAME."
    echo "Valid cluster budgets and authorized users:"
    if [[ -f "/fsx/references/runtime_assets/budget_tags/pcluster-project-budget-tags.tsv" ]]; then
        cat "/fsx/references/runtime_assets/budget_tags/pcluster-project-budget-tags.tsv"
    else
        echo "Budget tags file not found."
    fi
    echo ""
    echo "Valid regions: Use a valid AWS region (e.g., us-east-1, us-west-2)."
    return 3
}

# Function to check if a command exists
command_exists() {
    command -v "$1" &> /dev/null
}

cluster_config_tag_value() {
    local tag_key="$1"
    local config_file="${2:-/opt/parallelcluster/shared/cluster-config.yaml}"
    if [[ ! -f "$config_file" ]]; then
        return 1
    fi
    awk -v tag_key="$tag_key" '
        $1 == "-" && $2 == "Key:" && $3 == tag_key {
            getline
            if ($1 == "Value:") {
                print $2
                found = 1
                exit
            }
        }
        END { exit(found ? 0 : 1) }
    ' "$config_file"
}

day_current_user() {
    local current_user="${USER:-}"
    if [[ -z "$current_user" ]]; then
        current_user="$(id -un 2>/dev/null || true)"
    fi
    if [[ -z "$current_user" ]]; then
        return 1
    fi
    printf "%s\n" "$current_user"
}

# Ensure AWS CLI is installed
if ! command_exists aws; then
    echo "Error: AWS CLI is not installed. Please install it first."
    return 3
fi

# Ensure conda is available
if ! command_exists conda; then
    echo "Error: conda is not available in PATH. Please install or load conda before continuing."
    return 3
fi

# Parse input arguments.  The canonical identities are supplied by DYEC.  The
# legacy --project option is retained only as an explicit, warned alias for
# the cluster budget name; legacy environment variables are cost-center
# aliases only and are never exported back to child processes.
SKIP_CLUSTER_BUDGET_CHECK=false
STRICT_CLUSTER_BUDGET_CHECK=false
DEACTIVATE=false
while [[ "$#" -gt 0 ]]; do
    case "$1" in
        --cluster-budget-name)
            if [[ -z "${2:-}" ]]; then
                echo "Error: --cluster-budget-name requires a cluster name."
                return 3
            fi
            cluster_budget_arg="$2"
            shift 2
            ;;
        --cost-center)
            if [[ -z "${2:-}" ]]; then
                echo "Error: --cost-center requires a cost-center name."
                return 3
            fi
            cost_center_arg="$2"
            shift 2
            ;;
        --project)
            if [[ -z "${2:-}" ]]; then
                echo "Error: --project requires a cluster name."
                return 3
            fi
            if [[ -n "$legacy_project_arg" && "$legacy_project_arg" != "$2" ]]; then
                echo "Error: repeated deprecated --project values disagree."
                return 3
            fi
            legacy_project_arg="$2"
            echo "Warning: --project is deprecated; use --cluster-budget-name." >&2
            shift 2
            ;;
        --skip-cluster-budget-check)
            if [[ "$STRICT_CLUSTER_BUDGET_CHECK" == true ]]; then
                echo "Error: --skip-cluster-budget-check conflicts with --strict-cluster-budget-check."
                return 3
            fi
            SKIP_CLUSTER_BUDGET_CHECK=true
            shift
            ;;
        --strict-cluster-budget-check)
            if [[ "$SKIP_CLUSTER_BUDGET_CHECK" == true ]]; then
                echo "Error: --strict-cluster-budget-check conflicts with --skip-cluster-budget-check."
                return 3
            fi
            STRICT_CLUSTER_BUDGET_CHECK=true
            shift
            ;;
        --deactivate)
            DEACTIVATE=true
            shift
            ;;          
        -h|--help|help)
            usage
            return 0
            ;;
        *)
            echo "Unknown parameter passed: $1"
            usage
            return 3
            ;;
    esac
done

if [[ "$DAYOA_MAC_LOCAL" == true ]]; then
    if [[ "${CONDA_DEFAULT_ENV:-}" != "DAY-EC" && "${CONDA_DEFAULT_ENV:-}" != "DAYOA" ]]; then
        echo "Error: macOS local mode requires the DAY-EC or DAYOA conda environment."
        echo "Run: conda activate DAY-EC"
        return 3
    fi
    SKIP_CLUSTER_BUDGET_CHECK=true
fi

# Check if DEACTIVATE flag is set
if [[ "$DEACTIVATE" == true ]]; then
    echo "Deactivating existing environments..."
    source bin/day_deactivate &> /dev/null || {
        echo "Error during environment deactivation."
        return 4
    }
    echo "Environment deactivated successfully."
fi


# Resolve the exact cluster budget identity and the execution cost center.
cluster_config_file="/opt/parallelcluster/shared/cluster-config.yaml"
CLUSTER_BUDGET_ENFORCEMENT=""
configured_cluster_budget=""
if [[ -f "$cluster_config_file" ]]; then
    CLUSTER_BUDGET_ENFORCEMENT="$(cluster_config_tag_value "aws-parallelcluster-enforce-budget" "$cluster_config_file" || true)"
    configured_cluster_budget="$(cluster_config_tag_value "aws-parallelcluster-project" "$cluster_config_file" || true)"
fi

if [[ -n "$cluster_budget_arg" && -n "$canonical_budget_env" && "$cluster_budget_arg" != "$canonical_budget_env" ]]; then
    echo "Error: --cluster-budget-name conflicts with DYEC_CLUSTER_BUDGET_NAME."
    return 3
fi
if [[ -n "$cluster_budget_arg" && -n "$legacy_project_arg" && "$cluster_budget_arg" != "$legacy_project_arg" ]]; then
    echo "Error: --cluster-budget-name conflicts with deprecated --project."
    return 3
fi
if [[ -n "$legacy_project_arg" && -n "$canonical_budget_env" && "$legacy_project_arg" != "$canonical_budget_env" ]]; then
    echo "Error: deprecated --project conflicts with DYEC_CLUSTER_BUDGET_NAME."
    return 3
fi
if [[ -n "$cost_center_arg" && -n "$canonical_cost_center_env" && "$cost_center_arg" != "$canonical_cost_center_env" ]]; then
    echo "Error: --cost-center conflicts with DYEC_COST_CENTER_NAME."
    return 3
fi

cluster_budget_name="${cluster_budget_arg:-${legacy_project_arg:-$canonical_budget_env}}"
if [[ -z "$cluster_budget_name" ]]; then
    if [[ "$DAYOA_MAC_LOCAL" == true ]]; then
        cluster_budget_name="dayoa-local-mac"
        echo "Notice: macOS local mode active. Using cluster budget: $cluster_budget_name"
    else
        echo "Error: --cluster-budget-name or DYEC_CLUSTER_BUDGET_NAME is required on a remote headnode."
        return 3
    fi
fi

if [[ -n "$configured_cluster_budget" && "$cluster_budget_name" != "$configured_cluster_budget" ]]; then
    echo "Error: cluster budget '$cluster_budget_name' does not exactly match cluster '$configured_cluster_budget'."
    return 3
fi
if [[ "$CLUSTER_BUDGET_ENFORCEMENT" == "skip" && "$SKIP_CLUSTER_BUDGET_CHECK" == false && "$STRICT_CLUSTER_BUDGET_CHECK" == false ]]; then
    echo "Notice: cluster config sets aws-parallelcluster-enforce-budget=skip; skipping cluster-budget validation."
    SKIP_CLUSTER_BUDGET_CHECK=true
fi

legacy_cost_center=""
if [[ -n "$legacy_day_project_env" ]]; then
    echo "Warning: DAY_PROJECT is deprecated; use DYEC_COST_CENTER_NAME." >&2
    legacy_cost_center="$legacy_day_project_env"
fi
if [[ -n "$legacy_daylily_cost_center_env" ]]; then
    echo "Warning: DAYLILY_COST_CENTER is deprecated; use DYEC_COST_CENTER_NAME." >&2
    if [[ -n "$legacy_cost_center" && "$legacy_cost_center" != "$legacy_daylily_cost_center_env" ]]; then
        echo "Error: DAY_PROJECT and DAYLILY_COST_CENTER disagree."
        return 3
    fi
    legacy_cost_center="$legacy_daylily_cost_center_env"
fi

cost_center_name="${cost_center_arg:-$canonical_cost_center_env}"
if [[ -n "$cost_center_name" && -n "$legacy_cost_center" && "$cost_center_name" != "$legacy_cost_center" ]]; then
    echo "Error: DYEC_COST_CENTER_NAME conflicts with a deprecated cost-center alias."
    return 3
fi
if [[ -z "$cost_center_name" ]]; then
    cost_center_name="$legacy_cost_center"
fi

# Display and export only canonical execution identities.  A remote Slurm
# activation performs the required non-empty check in bin/day_activate.
echo "Cluster Budget: $cluster_budget_name"
echo "Cost Center: ${cost_center_name:-<required for remote Slurm>}"
echo "Skip Cluster Budget Check: $SKIP_CLUSTER_BUDGET_CHECK"
echo "Strict Cluster Budget Check: $STRICT_CLUSTER_BUDGET_CHECK"

# Export canonical environment variables and bind their deterministic context.
export DYEC_CLUSTER_BUDGET_NAME="$cluster_budget_name"
if [[ -n "$cost_center_name" ]]; then
    export DYEC_COST_CENTER_NAME="$cost_center_name"
else
    unset DYEC_COST_CENTER_NAME
fi
unset PROJECT DAY_PROJECT DAYLILY_COST_CENTER
unset TOTAL_BUDGET USED_BUDGET PERCENT_USED
export DAY_AWS_REGION="$region"
export AWS_ACCOUNT_ID="NA"

if [[ -n "${DYEC_CLUSTER_BUDGET_NAME:-}" && -n "${DYEC_COST_CENTER_NAME:-}" ]]; then
    _dayoa_cost_context_json="$(python3 -m daylily_omics_analysis.cost_context --execution local)" || {
        echo "Error: unable to resolve the canonical DYEC cost context."
        return 3
    }
    DYEC_COST_CONTEXT_SHA256="$(printf '%s' "$_dayoa_cost_context_json" | python3 -c 'import json, sys; print(json.load(sys.stdin)["context_sha256"])')" || {
        echo "Error: unable to extract the canonical DYEC cost-context hash."
        return 3
    }
    export DYEC_COST_CONTEXT_SHA256
else
    unset DYEC_COST_CONTEXT_SHA256
fi

# Skip cluster-budget check if the flag is provided
if [[ "$SKIP_CLUSTER_BUDGET_CHECK" == false || "$STRICT_CLUSTER_BUDGET_CHECK" == true ]]; then
    CURRENT_USER="$(day_current_user)"
    if [[ -z "$CURRENT_USER" ]]; then
        echo "Error: USER is not set and id -un failed; cannot validate cluster budget authorization."
        return 3
    fi

    # Path to the budget file
    budget_file="/fsx/references/runtime_assets/budget_tags/pcluster-project-budget-tags.tsv"

    # Ensure the budget file exists
    if [[ ! -f "$budget_file" ]]; then
        echo "Error: Budget file '$budget_file' not found."
        return 3
    fi

    # Validate the cluster budget for the current user
    AUTHORIZED_CLUSTER_BUDGETS=$(awk -F'\t' -v user="$CURRENT_USER" '$2 ~ user {print $1}' "$budget_file" | tr '\n' ',' | sed 's/,$//')
    if [[ ! ",$AUTHORIZED_CLUSTER_BUDGETS," =~ ",$cluster_budget_name," ]]; then
        echo "Error: cluster budget '$cluster_budget_name' is not valid for user '$CURRENT_USER'."
        echo "Valid cluster budgets for '$CURRENT_USER': $AUTHORIZED_CLUSTER_BUDGETS"
        return 3
    fi
else
    echo "Skipping cluster-budget validation as --skip-cluster-budget-check was passed."
fi

# Function to create a new AWS budget
create_budget() {
    echo "To create a budget, please exit and run the following command:"
    echo "bash bin/create_budget.sh --help"
    echo "Then append the new project/budget name to /fsx/references/runtime_assets/budget_tags/pcluster-project-budget-tags.tsv."
    echo "Note: /fsx/references/runtime_assets is read-only; update the file via S3."

}

is_nonnegative_number() {
    [[ "$1" =~ ^[0-9]+([.][0-9]+)?$ ]]
}

export DYEC_CLUSTER_BUDGET_LIMIT="NA"
export DYEC_CLUSTER_BUDGET_USED="NA"
export DYEC_CLUSTER_BUDGET_PERCENT_USED="NA"

if [[ "$SKIP_CLUSTER_BUDGET_CHECK" == true && "$STRICT_CLUSTER_BUDGET_CHECK" == false ]]; then
    echo ""
    echo "________________________________________________________"
    echo "AWS budget lookup skipped for cluster '$cluster_budget_name' in region '$region'."
    echo "  Limit: $DYEC_CLUSTER_BUDGET_LIMIT"
    echo "  Used: $DYEC_CLUSTER_BUDGET_USED"
    echo "  Percent Used: $DYEC_CLUSTER_BUDGET_PERCENT_USED"
    echo "________________________________________________________"
else
    # Get AWS Account ID
    export AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query "Account" --output text)
    if [[ -z "$AWS_ACCOUNT_ID" ]]; then
        echo "Error: Unable to retrieve AWS Account ID."
        return 3
    fi

    if ! command_exists jq; then
        echo "Error: jq is required to parse AWS budget JSON."
        return 3
    fi

    # Query AWS budgets
    BUDGETS=$(aws budgets describe-budgets --account-id "$AWS_ACCOUNT_ID" --region "$region" 2>/dev/null)
    budgets_ret=$?

    if [[ "$budgets_ret" -ne 0 || -z "$BUDGETS" ]]; then
        echo "Error: Unable to retrieve AWS budgets. Please check your AWS permissions or configuration."
        return 3
    fi

    if ! echo "$BUDGETS" | jq -e '.Budgets | type == "array"' >/dev/null 2>&1; then
        echo "Error: AWS budget response was missing a Budgets array."
        return 3
    fi

    # Check if the specified cluster budget exists
    MATCHING_CLUSTER_BUDGET=$(echo "$BUDGETS" | jq -c --arg cluster_budget "$cluster_budget_name" '[.Budgets[] | select(.BudgetName==$cluster_budget)] | if length == 1 then .[0] else empty end')

    if [[ -z "$MATCHING_CLUSTER_BUDGET" ]]; then
        echo "No matching AWS budget found for cluster '$cluster_budget_name' in region '$region'."
        echo "Available AWS budgets (specify with --cluster-budget-name):"
        echo "$BUDGETS" | jq -r '.Budgets[].BudgetName'

        read -p "Would you like to create a new budget? (y/n): " RESPONSE
        if [[ "$RESPONSE" =~ ^[Yy]$ ]]; then
            create_budget
        else
            echo "Exiting without creating a budget."
        fi
        return 3
    fi

    # Extract budget details
    cluster_budget_limit=$(echo "$MATCHING_CLUSTER_BUDGET" | jq -r ".BudgetLimit.Amount // empty")
    cluster_budget_used=$(echo "$MATCHING_CLUSTER_BUDGET" | jq -r ".CalculatedSpend.ActualSpend.Amount // empty")

    if ! is_nonnegative_number "$cluster_budget_limit" || ! is_nonnegative_number "$cluster_budget_used"; then
        echo "Error: AWS budget response did not include numeric limit and spend values for cluster '$cluster_budget_name'."
        return 3
    fi

    if ! awk -v total="$cluster_budget_limit" 'BEGIN { exit (total > 0 ? 0 : 1) }'; then
        echo "Error: AWS budget limit for cluster '$cluster_budget_name' must be greater than zero."
        return 3
    fi

    # Calculate usage percentage
    cluster_budget_percent_used=$(awk -v used="$cluster_budget_used" -v total="$cluster_budget_limit" 'BEGIN { printf "%.2f", (used / total) * 100 }')
    percent_ret=$?
    if [[ "$percent_ret" -ne 0 || -z "$cluster_budget_percent_used" ]]; then
        echo "Error: Unable to calculate budget usage percentage for cluster '$cluster_budget_name'."
        return 3
    fi

    export DYEC_CLUSTER_BUDGET_LIMIT="$cluster_budget_limit"
    export DYEC_CLUSTER_BUDGET_USED="$cluster_budget_used"
    export DYEC_CLUSTER_BUDGET_PERCENT_USED="$cluster_budget_percent_used"

    # Display budget information
    echo ""
    echo "________________________________________________________"
    echo "AWS budget for cluster '$cluster_budget_name' in region '$region':"
    echo "  Limit: $DYEC_CLUSTER_BUDGET_LIMIT USD"
    echo "  Used: $DYEC_CLUSTER_BUDGET_USED USD"
    echo "  Percent Used: $DYEC_CLUSTER_BUDGET_PERCENT_USED%"
    echo "________________________________________________________"

    if awk -v pct="$DYEC_CLUSTER_BUDGET_PERCENT_USED" 'BEGIN { exit (pct >= 80 ? 0 : 1) }'; then
        echo "Warning: cluster budget '$cluster_budget_name' is at or above 80% usage."
    fi
    if awk -v pct="$DYEC_CLUSTER_BUDGET_PERCENT_USED" 'BEGIN { exit (pct >= 100 ? 0 : 1) }'; then
        if [[ "${DAY_PASS_ON_BUDGET_EXCEEDED:-}" == "true" ]]; then
            echo "Warning: cluster budget '$cluster_budget_name' is exhausted; explicit warning-only override is active."
        else
            echo "Error: cluster budget '$cluster_budget_name' is exhausted."
            return 3
        fi
    fi
fi

# Set environment variables
DAY_USER="$(day_current_user)"
if [[ -z "$DAY_USER" ]]; then
    echo "Error: USER is not set and id -un failed; cannot initialize APPTAINER_HOME."
    return 3
fi
export USER="${USER:-$DAY_USER}"
export DAY_ROOT="$PWD"
if [[ "$DAYOA_MAC_LOCAL" == true ]]; then
    export DAY_BIOME="MAC"
    export DAYOA_MAC_STATE_DIR="${DAYOA_MAC_STATE_DIR:-$DAY_ROOT/.dayoa-local-mac}"
    export APPTAINER_HOME="$DAYOA_MAC_STATE_DIR/apptainer_home/$DAY_USER/$(hostname)/"
else
    export DAY_BIOME="AWSPC"
    export APPTAINER_HOME="/fsx/resources/environments/containers/$DAY_USER/$(hostname)/"
fi

# Increase file descriptor limit
ulimit -n 16384

# Set Sentieon variables and require the dedicated license-server contract.
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

if [[ "$DAYOA_MAC_LOCAL" == true ]]; then
    export SENTIEON_TMPDIR="$DAYOA_MAC_STATE_DIR/sentieon_tmp"
    export SENTIEON_INSTALL_DIR=""
    sentieon_config_file="${DAYLILY_CLI_GLOBAL_CONFIG:-$DAY_ROOT/config/daylily_cli_global.yaml}"
else
    export SENTIEON_TMPDIR='/dev/shm/'
    export SENTIEON_INSTALL_DIR='/fsx/references/runtime_assets/cached_envs/sentieon-genomics-202503.04'
    export PATH="$PATH:$SENTIEON_INSTALL_DIR/bin/"
    sentieon_config_file="${DAYLILY_CLI_GLOBAL_CONFIG:-$HOME/.config/daylily/daylily_cli_global.yaml}"
fi
dayoa_resolve_sentieon_license_endpoint "$sentieon_config_file" || return 3

# Backup original PATH and PS1 if not already set
export ORIG_PATH="${ORIG_PATH:-$PATH}"
export ORIG_PS1="${ORIG_PS1:-${PS1:-}}"

# Source color themes
if [[ -f "config/cli/colr_themes.sh" ]]; then
    source "config/cli/colr_themes.sh"
else
    echo "Warning: Color themes file not found at config/cli/colr_themes.sh"
fi
if ! command_exists colr; then
    colr() {
        if [[ "${1:-}" == "-n" ]]; then
            shift
            printf "%s" "${1:-}"
        else
            printf "%s\n" "${1:-}"
        fi
    }
fi

# Warn if shell is not bash
if [[ "${SHELL:-}" != *"bash"* && "$DAYOA_MAC_LOCAL" == false ]]; then
    echo "Warning: This script has only been tested with bash."
    sleep 10
fi

# Update PATH
export PATH="$PATH:$PWD/bin"

# Source tab completion script
if [[ -f "bin/tabcomp.bash" ]]; then
    if command_exists complete; then
        source "bin/tabcomp.bash"
    elif [[ "$DAYOA_MAC_LOCAL" == true ]]; then
        echo "Notice: Bash tab completion is not available in this shell; skipping bin/tabcomp.bash."
    else
        echo "Warning: Bash tab completion is not available in this shell; skipping bin/tabcomp.bash."
    fi
else
    echo "Warning: Tab completion script not found at bin/tabcomp.bash"
fi

# Define aliases
alias day-activate="source bin/day_activate"
alias day-deactivate="source bin/day_deactivate"
alias day-monitor="bin/day_monitor"
alias dy-a="source bin/day_activate"
alias dy-d="source bin/day_deactivate"
alias dy-r="bin/dy_run"
alias dy-m="bin/day_monitor"
alias dy-h="bin/dy_run help"
alias day-set-genome-build="source bin/day_set_genome_build"
alias dy-g="source bin/day_set_genome_build"


# Display help if requested
if [[ "${1:-}" =~ ^(-h|--help|help)$ ]]; then
    if [[ -f "docs/markdown/cli_help_brief.md" ]]; then
        hlp=$(cat docs/markdown/cli_help_brief.md)
        if command_exists colr; then
            colr """$hlp""" "floralwhite" "midnightblue" "b"
        else
            echo "$hlp"
        fi
    else
        echo "Help file not found at docs/markdown/cli_help_brief.md"
    fi
    return 0
fi

if [[ "$DAYOA_MAC_LOCAL" == true ]]; then
    if ! conda env list | awk '{print $1}' | grep -Fx "DAYOA" >/dev/null 2>&1; then
        echo "Error: macOS local mode requires the DAYOA conda environment."
        echo "Install it with: source config/day/day_env_installer.sh DAYOA"
        return 1
    fi
    conda activate DAYOA || {
        echo "Error: Failed to activate 'DAYOA' conda environment."
        return 1
    }
    echo "macOS local mode: using conda environment DAYOA."
else
    DAYOA_ENV_CONTRACT="config/day/day_env_contract.sh"
    if [[ ! -f "$DAYOA_ENV_CONTRACT" ]]; then
        echo "Error: DAYOA environment contract is missing: $DAYOA_ENV_CONTRACT"
        return 1
    fi
    source "$DAYOA_ENV_CONTRACT" || {
        echo "Error: Failed to load DAYOA environment contract: $DAYOA_ENV_CONTRACT"
        return 1
    }

    conda env list
    # Create DAYOA only when the environment itself is absent. An existing
    # environment is activated as-is; no Mermaid/Chrome readiness probe or
    # installer re-entry occurs during initialization.
    if ! conda env list | awk '{print $1}' | grep -Fx "DAYOA" >/dev/null 2>&1; then
        echo "!Conda environment 'DAYOA' not found. Building it now..."
        echo " ... you might need to start from a new shell."

        source config/day/day_env_installer.sh DAYOA
        if [[ "$?" != "0" ]]; then
            echo "Error: Failed to install the DAYOA environment. - $!"
            return 1
        else
            echo "DAYOA install success"
        fi
    else
        echo "DAYOA environment already exists; activating without rebuilding its runtime."
    fi

    conda activate DAYOA || {
        echo "Error: Failed to activate 'DAYOA' conda environment."
        return 1
    }

    dayoa_export_mermaid_browser || {
        echo "Error: Failed to select the declared DAYOA Chrome headless shell path."
        return 1
    }
fi


# Final message
echo "Day CLI initialized for cluster '$cluster_budget_name' and cost center '${cost_center_name:-<unset>}' in region '$region'."
echo -e "The Daylily CLI is now available."
echo -e "Available commands (tab completion is enabled for all):"
echo  " "
echo -e "\t(day-activate / dy-a) [slurm|local] ([hg38|hg38_broad|b37])- Activate a Slurm or local environment."
echo -e "\t                           "
echo -e "\t{day-set-genome-build / dy-g) [b37|hg38|hg38_broad] - Set the genome build for the current environment."
echo -e "\t                           "
echo -e "\t(dy-r)                  - Run a command in the current environment."
echo -e "\t                           <tab> for exposed targets, -<tab> for all command line flags."
echo -e "\t                           "
echo -e "\t(day-monitor / dy-m)      - Monitor workflow status (Snakemake, SLURM, logs)."
echo -e "\t                           Use --block-and-poll to wait for completion."
echo -e "\t                           "
echo -e "\t(day-deactivate / dy-d)   - Deactivate the current environment."
echo -e "\t                           Use 'dy-d reset' to hard reset the environment."
echo -e "\t                           "
echo -e "\t                           "
echo -e "\t                           "
echo -e "\t                           "
echo -e "\t. To Stage Sample Data, see daylily-ephemeral-cluster docs for running ~/projects/daylily-ephemeral-cluster/bin/daylily-stage-analysis-samples-headnode "
echo -e "\t  ... which once run, you will copy specimens.tsv, samples.tsv, and libraries.tsv to config/ in this directory."
echo -e "\t                           "
echo -e "\t(example): ACTIVATE AN ANALYSIS ENV\n"
echo -e "\n"
echo -e "\n"
echo -e "\t\tdy-a slurm hg38 # or hg38_broad or b37\n"

echo -e "\t(example): RUN ANALYSES\n"
echo -e "\t\tcp .test_data/data/0.01xwgs_HG002_hg38.specimens.tsv config/specimens.tsv\n"
echo -e "\t\tcp .test_data/data/0.01xwgs_HG002_hg38.v12.samples.tsv config/samples.tsv\n"
echo -e "\t\tcp .test_data/data/0.01xwgs_HG002_hg38.libraries.tsv config/libraries.tsv\n"
echo -e "\n"
echo -e "\t\t# Use target names directly (tab-complete available):\n"
echo -e "\t\tdy-r produce_snv_concordances -p -k -j 20 -n   # Illumina short-read SNV concordance\n"
echo -e "\t\tdy-r produce_alignstats -p -k -j 20 -n         # Alignment statistics\n"
echo -e "\n"
echo -e "\t\t# Platform-specific targets:\n"
echo -e "\t\tdy-r produce_sentdont_vcf -p -k -j 20 -n       # ONT SNV calling\n"
echo -e "\t\tdy-r produce_sentdpb_vcf -p -k -j 20 -n        # PacBio SNV calling\n"
echo -e "\t\tdy-r produce_sentdug_vcf -p -k -j 20 -n        # Ultima SNV calling (use hg38_broad)\n"
echo -e "\n"
echo -e "\t\t# Hybrid workflow targets:\n"
echo -e "\t\tdy-r produce_sentdhio_vcf -p -k -j 20 -n       # Hybrid Illumina+ONT CLI\n"
echo -e "\t\tdy-r produce_sentdhuo_vcf -p -k -j 20 -n       # Hybrid Ultima+ONT CLI (use hg38_broad)\n"
echo -e "\t\tdy-r produce_sentdhiom_vcf -p -k -j 20 -n      # Hybrid Illumina+ONT Modular\n"
echo -e "\t\tdy-r produce_sentdhuom_vcf -p -k -j 20 -n      # Hybrid Ultima+ONT Modular (use hg38_broad)\n"
echo -e "\n"
echo -e "\t\t# Remove -n to execute (not dry-run)\n"

return 0
