#!/bin/bash

# Enable strict mode to exit on errors and unset variables
set -euo pipefail

# Set log file
LOG_FILE="/tmp/mcp.log"

# Clear the log file at the start
> "$LOG_FILE"

# Function for logging
log() {
    local MESSAGE="$1"
    echo "$(date +'%Y-%m-%d %H:%M:%S') - $MESSAGE" | tee -a "$LOG_FILE" >&2
}

# Trap errors and log them before exiting
trap 'log "An error occurred. Exiting with status $?."' ERR

log "Starting uvx setup script."

if [ -n "${GOOSE_PATH_ROOT:-}" ]; then
    RESOLVED_GOOSE_CONFIG_DIR="${GOOSE_PATH_ROOT}/config"
elif [ -n "${GOOSE_CONFIG_DIR:-}" ]; then
    log "GOOSE_CONFIG_DIR is deprecated for desktop shims; prefer GOOSE_PATH_ROOT."
    RESOLVED_GOOSE_CONFIG_DIR="${GOOSE_CONFIG_DIR}"
else
    RESOLVED_GOOSE_CONFIG_DIR="${HOME}/.config/goose"
fi
MCP_HERMIT_DIR="${RESOLVED_GOOSE_CONFIG_DIR}/mcp-hermit"

# Ensure mcp-hermit/bin exists
log "Creating directory ${MCP_HERMIT_DIR}/bin if it does not exist."
mkdir -p "${MCP_HERMIT_DIR}/bin"

# Change to the mcp-hermit directory
log "Changing to directory ${MCP_HERMIT_DIR}."
cd "${MCP_HERMIT_DIR}"

# Check if hermit binary exists and download if not
if [ ! -f "${MCP_HERMIT_DIR}/bin/hermit" ]; then
    log "Hermit binary not found. Downloading hermit binary."
    curl -fsSL "https://github.com/cashapp/hermit/releases/download/stable/hermit-$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m | sed 's/x86_64/amd64/' | sed 's/aarch64/arm64/').gz" \
        | gzip -dc > "${MCP_HERMIT_DIR}/bin/hermit" && chmod +x "${MCP_HERMIT_DIR}/bin/hermit"
    log "Hermit binary downloaded and made executable."
else
    log "Hermit binary already exists. Skipping download."
fi


log "setting hermit cache to be local for MCP servers"
mkdir -p "${MCP_HERMIT_DIR}/cache"
export HERMIT_STATE_DIR="${MCP_HERMIT_DIR}/cache"

# Update PATH
export PATH="${MCP_HERMIT_DIR}/bin:${PATH}"
log "Updated PATH to include ${MCP_HERMIT_DIR}/bin."


# Verify hermit installation
log "Checking for hermit in PATH."
which hermit >> "$LOG_FILE"

# Initialize hermit
log "Initializing hermit."
hermit init >> "$LOG_FILE"

# Initialize python >= 3.10
log "hermit install python 3.10"
hermit install python3@3.10 >> "$LOG_FILE"

# Install UV for python using hermit
log "Installing UV with hermit."
hermit install uv >> "$LOG_FILE"

# Verify installations
log "Verifying installation locations:"
log "hermit: $(which hermit)"
log "uv: $(which uv)"
log "uvx: $(which uvx)"


log "Checking for GOOSE_UV_REGISTRY environment variable for custom python/pip/UV registry setup..."
# Check if GOOSE_UV_REGISTRY is set and accessible
if [ -n "${GOOSE_UV_REGISTRY:-}" ] && curl -s --head --fail "$GOOSE_UV_REGISTRY" > /dev/null; then
    log "Checking custom goose registry availability: $GOOSE_UV_REGISTRY"
    log "$GOOSE_UV_REGISTRY is accessible, setting it as UV_INDEX_URL. Setting UV_NATIVE_TLS to true."
    export UV_INDEX_URL="$GOOSE_UV_REGISTRY"
    export UV_NATIVE_TLS=true
else
    log "Neither GOOSE_UV_REGISTRY nor UV_INDEX_URL is set. Falling back to default configuration."
fi

# Final step: Execute uvx with passed arguments
log "Executing 'uvx' command with arguments: $*"
uvx "$@" || log "Failed to execute 'uvx' with arguments: $*"

log "uvx setup script completed successfully."
