#!/usr/bin/env bash
set -euo pipefail

is_sourced=0
if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then
  is_sourced=1
fi

die() {
  local msg="$1"
  local code="${2:-1}"
  echo "$msg" >&2
  if [[ "$is_sourced" -eq 1 ]]; then
    return "$code"
  fi
  exit "$code"
}

usage() {
  cat <<'EOF'
Usage: init_dayec [-h|--help]

Create (or update) the DAY-EC conda environment and install daylily-ephemeral-cluster into it.

Behavior:
  - If run from a repo checkout (pyproject.toml present), performs an editable install.
  - Otherwise, installs from pip using DAYLILY_EC_INIT_DAYEC_PIP_SPEC if set,
    else attempts to install by package name (requires the package to be available on your index).

Environment:
  DAYLILY_EC_INIT_DAYEC_PIP_SPEC   Pip install spec (e.g. git+https://...@<ref>).
  DAYLILY_EC_RESOURCES_DIR         Overrides packaged resource lookup for config/day/daycli.yaml.
EOF
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  if [[ "$is_sourced" -eq 1 ]]; then
    return 0
  fi
  exit 0
fi

resolve_daylily_res_dir() {
  if [[ -n "${DAYLILY_EC_RESOURCES_DIR:-}" ]]; then
    echo "${DAYLILY_EC_RESOURCES_DIR}"
    return 0
  fi
  if command -v daylily-ec >/dev/null 2>&1; then
    daylily-ec resources-dir
    return 0
  fi
  local script_dir repo_root
  script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  repo_root="$(cd "${script_dir}/.." && pwd)"
  if [[ -d "${repo_root}/config" && -d "${repo_root}/bin" ]]; then
    echo "${repo_root}"
    return 0
  fi
  return 1
}

RES_DIR="$(resolve_daylily_res_dir)" || die "Error: could not resolve Daylily resources dir. Set DAYLILY_EC_RESOURCES_DIR or install daylily-ephemeral-cluster."

mkdir -p "${HOME}/.config/daylily"

if ! command -v conda >/dev/null 2>&1; then
  if [[ -x "${RES_DIR}/bin/install_miniconda" ]]; then
    die "Error: conda is not available in this shell. Install Miniconda first (try: ${RES_DIR}/bin/install_miniconda)." 3
  fi
  die "Error: conda is not available in this shell. Install Miniconda first." 3
fi

CHANNELS_MAIN="https://repo.anaconda.com/pkgs/main"
CHANNELS_R="https://repo.anaconda.com/pkgs/r"

echo "Conda supports 'tos'; attempting programmatic acceptance (rerun-safe)..."
conda config --set always_yes true >/dev/null 2>&1 || true
conda tos accept --override-channels --channel "$CHANNELS_MAIN" >/dev/null 2>&1 || true
conda tos accept --override-channels --channel "$CHANNELS_R"    >/dev/null 2>&1 || true

env_exists=0
if conda env list 2>/dev/null | awk '{print $1}' | grep -qx DAY-EC; then
  env_exists=1
  echo "Conda environment 'DAY-EC' already exists."
else
  env_yaml="${RES_DIR}/config/day/daycli.yaml"
  if [[ ! -f "$env_yaml" ]]; then
    die "Error: expected conda env YAML not found: $env_yaml" 2
  fi
  echo "Creating 'DAY-EC' environment from ${env_yaml} ..."
  conda env create -y -n DAY-EC -f "$env_yaml"
fi

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "${script_dir}/.." && pwd)"

pip_args=()
install_desc=""
if [[ -f "${repo_root}/pyproject.toml" ]]; then
  pip_args+=(--editable "$repo_root")
  install_desc="editable install from repo checkout"
elif [[ -n "${DAYLILY_EC_INIT_DAYEC_PIP_SPEC:-}" ]]; then
  pip_args+=("${DAYLILY_EC_INIT_DAYEC_PIP_SPEC}")
  install_desc="pip spec from DAYLILY_EC_INIT_DAYEC_PIP_SPEC"
else
  pip_args+=(daylily-ephemeral-cluster)
  install_desc="package name (requires publishing)"
fi

echo "Installing daylily-ephemeral-cluster into DAY-EC via pip (${install_desc})..."
if ! conda run -n DAY-EC python -m pip install "${pip_args[@]}"; then
  echo "Error: pip install failed." >&2
  if [[ ! -f "${repo_root}/pyproject.toml" && -z "${DAYLILY_EC_INIT_DAYEC_PIP_SPEC:-}" ]]; then
    echo "Tip: set DAYLILY_EC_INIT_DAYEC_PIP_SPEC to a git+https://... spec, or run init_dayec from a repo checkout." >&2
  fi
  die "Failed to install daylily-ephemeral-cluster into DAY-EC." 1
fi

if [[ "$env_exists" -eq 1 ]]; then
  echo "Reinstalled daylily-ephemeral-cluster in the existing DAY-EC environment."
else
  echo "DAY-EC environment created successfully."
fi

echo "Daylily CLI environment is ready. Activate with:"
echo "  conda activate DAY-EC"

if [[ "$is_sourced" -eq 1 ]]; then
  # Best-effort activation for interactive sourcing.
  if command -v conda >/dev/null 2>&1; then
    eval "$(conda shell.bash hook)" >/dev/null 2>&1 || true
    conda activate DAY-EC >/dev/null 2>&1 || true
    if [[ "${CONDA_DEFAULT_ENV:-}" == "DAY-EC" ]]; then
      echo "✓ DAY-EC conda environment is now active."
    else
      echo "Warning: could not auto-activate DAY-EC in this shell; run 'conda activate DAY-EC'." >&2
    fi
  fi
fi

