#!/bin/sh
# Ursa Environment Activation Script
# ==========================================
# This script must be SOURCED, not executed:
#   source ./ursa_activate
#
# It will:
#   1. Build the URSA conda environment from config/ursa_env.yaml if it doesn't exist
#   2. Activate the URSA conda environment
#   3. Add the bin/ directory to PATH so the 'ursa' CLI is available
#
# Prerequisites:
#   - conda or mamba must be installed and available in PATH

# DO NOT use set -e when sourcing - it will exit the user's shell on any error!

# ========== Colors ==========
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m' # No Color

# ========== Configuration ==========
CONDA_ENV_NAME="URSA"

# When this file is sourced, `$0` refers to the user's shell (e.g. zsh), not
# this script. So we cannot reliably use `dirname "$0"` to locate the repo.
#
# Instead, search upwards from the current working directory for the expected
# repository layout (config/ursa_env.yaml). This keeps the script POSIX-sh
# compatible while working from subdirectories.
SCRIPT_DIR="$(pwd)"
while [ ! -f "${SCRIPT_DIR}/config/ursa_env.yaml" ] && [ "${SCRIPT_DIR}" != "/" ]; do
    SCRIPT_DIR="$(dirname "${SCRIPT_DIR}")"
done

ENV_FILE="${SCRIPT_DIR}/config/ursa_env.yaml"
VENV_BIN="${SCRIPT_DIR}/.venv/bin"

# ========== Helper Functions ==========
log_info() {
    printf "${CYAN}→${NC} %s\n" "$1"
}

log_success() {
    printf "${GREEN}✓${NC} %s\n" "$1"
}

log_warn() {
    printf "${YELLOW}⚠${NC} %s\n" "$1"
}

log_error() {
    printf "${RED}✗${NC} %s\n" "$1"
}

# ========== Check Prerequisites ==========

# Detect conda command (prefer mamba if available). If conda is unavailable or
# activation fails, we will fall back to the local .venv if present.
_URSA_ACTIVATE_OK=1
CONDA_CMD=""
if command -v mamba >/dev/null 2>&1; then
    CONDA_CMD="mamba"
elif command -v conda >/dev/null 2>&1; then
    CONDA_CMD="conda"
fi

if [ -z "$CONDA_CMD" ]; then
    log_warn "Neither conda nor mamba found; falling back to local .venv if available"
fi

if [ -n "$CONDA_CMD" ] && [ ! -f "$ENV_FILE" ]; then
    log_warn "Environment file not found: $ENV_FILE (will fall back to .venv if available)"
fi

# Only continue if prerequisites are met
if [ "$_URSA_ACTIVATE_OK" -eq 0 ]; then
    unset _URSA_ACTIVATE_OK
else

# ========== Build or Activate Environment ==========
printf "\n${BOLD}${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}\n"
printf "${BOLD}${BLUE}║          Ursa - Environment Activation               ║${NC}\n"
printf "${BOLD}${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}\n\n"


# Attempt conda activation first (if available and config exists), otherwise fall back to .venv.
if [ -n "$CONDA_CMD" ] && [ -f "$ENV_FILE" ]; then
    # Check if environment exists
    if $CONDA_CMD env list | grep -q "^${CONDA_ENV_NAME} "; then
        log_success "Environment '${CONDA_ENV_NAME}' already exists"
    else
        log_info "Environment '${CONDA_ENV_NAME}' not found. Building from ${ENV_FILE}..."
        log_info "This may take a few minutes..."

        if $CONDA_CMD env create -n "$CONDA_ENV_NAME" -f "$ENV_FILE"; then
            log_success "Environment '${CONDA_ENV_NAME}' created successfully"
        else
            log_warn "Failed to create conda environment (will fall back to .venv if available)"
            _URSA_ACTIVATE_OK=0
        fi
    fi

    # ========== Activate Environment ==========
    if [ "$_URSA_ACTIVATE_OK" -eq 1 ]; then
        log_info "Activating environment '${CONDA_ENV_NAME}'..."

        # Source conda shell functions if needed
        if [ -z "$CONDA_SHLVL" ]; then
            # Conda not initialized in current shell
            CONDA_BASE="$($CONDA_CMD info --base 2>/dev/null)"
            if [ -f "${CONDA_BASE}/etc/profile.d/conda.sh" ]; then
                . "${CONDA_BASE}/etc/profile.d/conda.sh"
            fi
        fi

        if conda activate "$CONDA_ENV_NAME" 2>/dev/null; then
            log_success "Activated conda environment: ${CONDA_ENV_NAME}"
        else
            log_warn "Failed to activate conda environment (will fall back to .venv if available)"
            _URSA_ACTIVATE_OK=0
        fi
    fi
else
    _URSA_ACTIVATE_OK=0
fi

if [ "$_URSA_ACTIVATE_OK" -eq 0 ]; then
    if [ -x "${VENV_BIN}/python" ]; then
        log_info "Falling back to repo-local Python at ${VENV_BIN}/python"
        export PATH="${VENV_BIN}:${PATH}"
        log_success "Using repo-local .venv on PATH"
        _URSA_ACTIVATE_OK=1
    else
        log_error "No usable environment found (conda unavailable/failed and ${VENV_BIN}/python missing)"
        _URSA_ACTIVATE_OK=0
    fi
fi

# ========== Setup PATH ==========
if [ "$_URSA_ACTIVATE_OK" -eq 1 ]; then
    # Add bin directory to PATH if not already there
    BIN_DIR="${SCRIPT_DIR}/bin"
    if [ -d "$BIN_DIR" ]; then
        case ":$PATH:" in
            *":${BIN_DIR}:"*)
                # Already in PATH
                ;;
            *)
                export PATH="${BIN_DIR}:${PATH}"
                log_success "Added ${BIN_DIR} to PATH"
                ;;
        esac
    fi

    # Also add the repo root for the ursa script
    case ":$PATH:" in
        *":${SCRIPT_DIR}:"*)
            ;;
        *)
            export PATH="${SCRIPT_DIR}:${PATH}"
            log_success "Added ${SCRIPT_DIR} to PATH"
            ;;
    esac

    # ========== Install Package in Development Mode ==========
    log_info "Installing ursa in development mode..."
    if pip install -e "${SCRIPT_DIR}" -q 2>/dev/null; then
        log_success "Package installed in development mode"
    else
        log_warn "Failed to install package - some features may not work"
    fi

    # ========== Check Ursa Config File ==========
    # XDG Base Directory convention: ~/.config/ursa/ursa-config.yaml
    URSA_CONFIG_FILE="${HOME}/.config/ursa/ursa-config.yaml"
    URSA_CONFIG_LEGACY="${HOME}/.ursa/ursa-config.yaml"
    URSA_CONFIG_EXAMPLE="${SCRIPT_DIR}/config/ursa-config.example.yaml"

    if [ -f "$URSA_CONFIG_FILE" ]; then
        log_success "Config file found: ${URSA_CONFIG_FILE}"
    elif [ -f "$URSA_CONFIG_LEGACY" ]; then
        log_warn "Config file found at legacy path: ${URSA_CONFIG_LEGACY}"
        printf "   Consider moving to: ${CYAN}mkdir -p ~/.config/ursa && mv ${URSA_CONFIG_LEGACY} ${URSA_CONFIG_FILE}${NC}\n"
    else
        log_warn "Config file not found: ${URSA_CONFIG_FILE}"
        printf "   Create it with: ${CYAN}mkdir -p ~/.config/ursa && cp ${URSA_CONFIG_EXAMPLE} ${URSA_CONFIG_FILE}${NC}\n"
    fi
fi

# ========== Tab Completion ==========
if [ "$_URSA_ACTIVATE_OK" -eq 1 ]; then
    # Enable Typer's built-in shell completion
    _ursa_shell="$(basename "$SHELL")"
    if [ "$_ursa_shell" = "zsh" ]; then
        eval "$(ursa --show-completion zsh 2>/dev/null)"
    elif [ "$_ursa_shell" = "bash" ]; then
        eval "$(ursa --show-completion bash 2>/dev/null)"
    fi

    log_success "Tab completion enabled for ursa CLI"

    # ========== Summary ==========
    printf "\n${BOLD}${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}\n"
    printf "${BOLD}${GREEN}║  ✓ Ursa environment ready!                                   ║${NC}\n"
    printf "${BOLD}${GREEN}╚══════════════════════════════════════════════════════════════╝${NC}\n\n"

    printf "  ${CYAN}Conda Environment:${NC} ${CONDA_ENV_NAME}\n"
    printf "  ${CYAN}Python:${NC}           $(python --version 2>&1 | cut -d' ' -f2)\n"
    printf "  ${CYAN}Project Root:${NC}     ${SCRIPT_DIR}\n"
    printf "\n"
    printf "  ${BOLD}Command Groups:${NC}\n"
    printf "    ${CYAN}ursa server${NC}   API server management (start, stop, status, logs)\n"
    printf "    ${CYAN}ursa monitor${NC}  Workset monitor (start, stop, status, logs)\n"
    printf "    ${CYAN}ursa aws${NC}      AWS resources (setup, status, teardown)\n"
    printf "    ${CYAN}ursa test${NC}     Testing (run, cov, lint, format, typecheck)\n"
    printf "    ${CYAN}ursa env${NC}      Environment (status, generate, clean)\n"
    printf "    ${CYAN}daycog${NC}        Cognito/SSO management via daylily-cognito\n"
    printf "\n"
    printf "  ${BOLD}Quick Start:${NC}\n"
    printf "    ursa --help           Show all commands\n"
    printf "    ursa server start     Start API server\n"
    printf "    ursa info             Show system status\n"
    printf "\n"
    printf "  ${BOLD}Tip:${NC} Use TAB to autocomplete ursa commands and subcommands\n"
    printf "\n"
    printf "  ${BOLD}Deactivate:${NC}\n"
    printf "    conda deactivate\n"
    printf "\n"
fi

# Close the main if block from prerequisites check
fi

# Cleanup
unset _URSA_ACTIVATE_OK
