#!/usr/bin/env bash
# Artemis CLI Installer
# Downloads and installs artemis-cli for the current platform
#
# Usage:
#   curl -L --digest -u "Artemis_User:Artemis_Custom_Runner_2025" \
#     "https://files.artemis.turintech.ai/public/artemis-cli/latest/artemis-cli-installer.sh" \
#     -o installer.sh && chmod +x installer.sh && ./installer.sh
#
# Or with version selection:
#   ./installer.sh                    # Newest stable release (default)
#   ./installer.sh --version 1.2.0    # Specific release
#   ./installer.sh --nightly          # Newest release incl. prereleases
#   ./installer.sh --dev              # Rolling development build
#
# Or with deployment selection (default: prod):
#   ./installer.sh --env dev                                # Dev deployment
#   ./installer.sh --env stg                                # Staging deployment
#   ./installer.sh --base-url http://alex.artemis.turintech.ai  # Custom deployment

set -e

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

# Configuration
BASE_URL="https://files.artemis.turintech.ai/public/artemis-cli"
BINARY_NAME="artemis"
AUTH_USER="Artemis_User"
AUTH_PASS="Artemis_Custom_Runner_2025"

# Default install directory - use ~/.local/bin (no sudo needed)
DEFAULT_INSTALL_DIR="$HOME/.local/bin"
INSTALL_DIR=""

# Version selection: empty = newest stable release
VERSION=""
DEV=false
NIGHTLY=false

# Deployment the CLI gets pointed at (named environment or full URL)
ENV="prod"

# Accept --flag=value as well as --flag value: split the former into the
# latter so the parser below only has to handle one shape.
args=()
for arg in "$@"; do
    case "$arg" in
        --*=*) args+=("${arg%%=*}" "${arg#*=}") ;;
        *)     args+=("$arg") ;;
    esac
done
set -- "${args[@]}"

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --version)
            VERSION="$2"
            shift 2
            ;;
        --dev)
            DEV=true
            shift
            ;;
        --nightly)
            NIGHTLY=true
            shift
            ;;
        --env)
            # Deployment to point the CLI at: dev, stg, prod, or a full
            # URL. Selects endpoints only - the build channel is chosen
            # with --version/--nightly/--dev.
            ENV="$2"
            shift 2
            ;;
        --install-dir)
            INSTALL_DIR="$2"
            shift 2
            ;;
        --base-url)
            # Same as --env with a full URL.
            ENV="$2"
            shift 2
            ;;
        --help|-h)
            echo "Artemis CLI Installer"
            echo ""
            echo "Usage: $0 [options]"
            echo ""
            echo "Options:"
            echo "  --version <X.Y.Z>       Install a specific release (default: newest stable)"
            echo "  --nightly               Install the newest release incl. prereleases"
            echo "  --dev                   Install the rolling development build"
            echo "  --env <env>             Deployment to point the CLI at: dev, stg, prod,"
            echo "                          or a full URL (default: prod)"
            echo "  --base-url <url>        Same as --env with a full URL"
            echo "                          (e.g., http://alex.artemis.turintech.ai)"
            echo "  --install-dir <dir>     Installation directory (default: ~/.local/bin)"
            echo "  --help, -h              Show this help message"
            echo ""
            echo "Examples:"
            echo "  $0                                              # Newest release, prod endpoints"
            echo "  $0 --version 1.2.0                              # Specific release"
            echo "  $0 --dev --env dev                              # Development build, dev endpoints"
            echo "  $0 --base-url http://alex.artemis.turintech.ai  # Custom endpoints"
            exit 0
            ;;
        *)
            echo -e "${RED}Unknown option: $1${NC}"
            exit 1
            ;;
    esac
done

# Set default install directory if not specified
if [ -z "$INSTALL_DIR" ]; then
    INSTALL_DIR="$DEFAULT_INSTALL_DIR"
fi

# Resolve the download channel from the version selection
SELECTED=0
[ "$DEV" = true ] && SELECTED=$((SELECTED + 1))
[ "$NIGHTLY" = true ] && SELECTED=$((SELECTED + 1))
[ -n "$VERSION" ] && SELECTED=$((SELECTED + 1))
if [ "$SELECTED" -gt 1 ]; then
    echo -e "${RED}--dev, --nightly and --version are mutually exclusive${NC}"
    exit 1
elif [ "$DEV" = true ]; then
    CHANNEL="dev"
elif [ "$NIGHTLY" = true ]; then
    CHANNEL="nightly"
elif [ -n "$VERSION" ]; then
    CHANNEL="${VERSION#v}"
else
    CHANNEL="latest"
fi

# Detect OS and architecture
detect_platform() {
    local os arch

    case "$(uname -s)" in
        Linux*)  os="linux" ;;
        Darwin*) os="darwin" ;;
        MINGW*|MSYS*|CYGWIN*) os="windows" ;;
        *)
            echo -e "${RED}Unsupported operating system: $(uname -s)${NC}"
            exit 1
            ;;
    esac

    case "$(uname -m)" in
        x86_64|amd64) arch="amd64" ;;
        arm64|aarch64) arch="arm64" ;;
        *)
            echo -e "${RED}Unsupported architecture: $(uname -m)${NC}"
            exit 1
            ;;
    esac

    echo "${os}-${arch}"
}

# Print banner
print_banner() {
    echo -e "${BLUE}"
    echo "╔═══════════════════════════════════════════════════════════╗"
    echo "║                    Artemis CLI Installer                  ║"
    echo "╚═══════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
}

# Check for required commands
check_requirements() {
    local missing=()

    if ! command -v curl &> /dev/null; then
        missing+=("curl")
    fi

    if [ ${#missing[@]} -ne 0 ]; then
        echo -e "${RED}Missing required commands: ${missing[*]}${NC}"
        echo "Please install them and try again."
        exit 1
    fi
}

# Download file with authentication
download_file() {
    local url="$1"
    local output="$2"

    curl -fL --digest -u "${AUTH_USER}:${AUTH_PASS}" \
        --progress-bar \
        "${url}" \
        -o "${output}"
}

# Verify checksum
verify_checksum() {
    local file="$1"
    local expected="$2"

    if command -v sha256sum &> /dev/null; then
        actual=$(sha256sum "$file" | awk '{print $1}')
    elif command -v shasum &> /dev/null; then
        actual=$(shasum -a 256 "$file" | awk '{print $1}')
    else
        echo -e "${YELLOW}Warning: Cannot verify checksum (sha256sum/shasum not found)${NC}"
        return 0
    fi

    if [ "$actual" = "$expected" ]; then
        return 0
    else
        echo -e "${RED}Checksum verification failed!${NC}"
        echo "Expected: $expected"
        echo "Got:      $actual"
        return 1
    fi
}

# Main installation
main() {
    print_banner
    check_requirements

    local platform=$(detect_platform)
    local binary_suffix=""

    if [[ "$platform" == windows-* ]]; then
        binary_suffix=".exe"
    fi

    local binary_file="artemis-cli-${platform}${binary_suffix}"
    local download_url="${BASE_URL}/${CHANNEL}/${binary_file}"
    local checksums_url="${BASE_URL}/${CHANNEL}/checksums.txt"

    echo -e "${BLUE}Platform:${NC} ${platform}"
    echo -e "${BLUE}Channel:${NC} ${CHANNEL}"
    echo -e "${BLUE}Install directory:${NC} ${INSTALL_DIR}"
    echo ""

    # Create temp directory
    local tmp_dir=$(mktemp -d)
    trap "rm -rf $tmp_dir" EXIT

    # Download checksums
    echo -e "${BLUE}Downloading checksums...${NC}"
    if ! download_file "${checksums_url}" "${tmp_dir}/checksums.txt" 2>/dev/null; then
        echo -e "${YELLOW}Warning: Could not download checksums, skipping verification${NC}"
    fi

    # Download binary
    echo -e "${BLUE}Downloading artemis-cli for ${platform}...${NC}"
    if ! download_file "${download_url}" "${tmp_dir}/${binary_file}"; then
        echo -e "${RED}Failed to download binary from ${download_url}${NC}"
        exit 1
    fi

    # Verify checksum if available
    if [ -f "${tmp_dir}/checksums.txt" ]; then
        echo -e "${BLUE}Verifying checksum...${NC}"
        expected_checksum=$(grep "${binary_file}" "${tmp_dir}/checksums.txt" | awk '{print $1}')
        if [ -n "$expected_checksum" ]; then
            if ! verify_checksum "${tmp_dir}/${binary_file}" "$expected_checksum"; then
                exit 1
            fi
            echo -e "${GREEN}Checksum verified!${NC}"
        fi
    fi

    # Install binary
    echo -e "${BLUE}Installing to ${INSTALL_DIR}/${BINARY_NAME}...${NC}"

    # Create install directory if it doesn't exist
    if [ ! -d "${INSTALL_DIR}" ]; then
        if ! mkdir -p "${INSTALL_DIR}" 2>/dev/null; then
            echo -e "${YELLOW}Creating ${INSTALL_DIR} requires sudo...${NC}"
            sudo mkdir -p "${INSTALL_DIR}"
        fi
    fi

    # Check if we need sudo
    if [ -w "${INSTALL_DIR}" ]; then
        mv "${tmp_dir}/${binary_file}" "${INSTALL_DIR}/${BINARY_NAME}${binary_suffix}"
        chmod +x "${INSTALL_DIR}/${BINARY_NAME}${binary_suffix}"
    else
        echo -e "${YELLOW}Installation to ${INSTALL_DIR} requires sudo...${NC}"
        echo -e "${YELLOW}You may be prompted for your password.${NC}"
        sudo mv "${tmp_dir}/${binary_file}" "${INSTALL_DIR}/${BINARY_NAME}${binary_suffix}"
        sudo chmod +x "${INSTALL_DIR}/${BINARY_NAME}${binary_suffix}"
    fi

    # Verify installation
    echo ""
    if command -v "${BINARY_NAME}" &> /dev/null; then
        echo -e "${GREEN}╔═══════════════════════════════════════════════════════════╗${NC}"
        echo -e "${GREEN}║           Artemis CLI installed successfully!             ║${NC}"
        echo -e "${GREEN}╚═══════════════════════════════════════════════════════════╝${NC}"
        echo ""
        echo -e "Version: $(${BINARY_NAME} version 2>/dev/null || echo 'unknown')"
        echo ""

        # Configure environment defaults
        configure_environment

        echo -e "${BLUE}Quick start:${NC}"
        echo "  artemis login          Connect and store your API key"
        echo "  artemis --help         Show available commands"
        echo "  artemis status         Check configuration status"
    else
        configure_environment

        echo -e "${YELLOW}Warning: Installation completed but '${BINARY_NAME}' not found in PATH${NC}"
        echo ""
        echo "Add ${INSTALL_DIR} to your PATH by running:"
        echo "  echo 'export PATH=\"\$PATH:${INSTALL_DIR}\"' >> ~/.bashrc"
        echo "  source ~/.bashrc"
        echo ""
        echo "Or run the binary directly:"
        echo "  ${INSTALL_DIR}/${BINARY_NAME} --help"
    fi
}

# Point the CLI at the selected deployment
configure_environment() {
    # Resolve named environments to their base URL; anything else is
    # taken as a full URL.
    local env_url
    case "$ENV" in
        dev)              env_url="http://dev.artemis.turintech.ai" ;;
        stg|staging)      env_url="https://staging.artemis.turintech.ai" ;;
        prod|production)  env_url="https://artemis.turintech.ai" ;;
        http://*|https://*) env_url="${ENV%/}" ;;
        *)
            echo -e "${YELLOW}Unknown environment '${ENV}' - expected dev, stg, prod, or a full URL.${NC}"
            echo -e "${YELLOW}Skipping endpoint configuration; run: artemis login --url <url>${NC}"
            echo ""
            return 0
            ;;
    esac

    # Write the config file directly rather than through the binary: older
    # releases seed missing configs with per-service dev URLs, which would
    # shadow the base URL we set here.
    local config_dir="$HOME/.config/artemis"
    local config_file="${config_dir}/.env"

    echo -e "${BLUE}Pointing the CLI at ${env_url}...${NC}"
    mkdir -p "$config_dir"
    touch "$config_file"

    # Per-service URL overrides shadow ARTEMIS_BASE_URL; drop them along
    # with any previous base URL, then set the new one.
    local tmp_file
    tmp_file=$(mktemp)
    grep -vE '^(ARTEMIS_BASE_URL|USER_MGMT_URL|AGENT_MGMT_URL|FALCON_URL|QUEST_URL|LLM_API_BASE_URL|CODE_WARDEN_URL)=' "$config_file" > "$tmp_file" || true
    printf 'ARTEMIS_BASE_URL=%s\n' "$env_url" >> "$tmp_file"
    mv "$tmp_file" "$config_file"
    chmod 600 "$config_file"

    echo -e "${GREEN}Endpoints configured (${env_url}).${NC}"
    echo -e "${YELLOW}Note: Finish setup with: artemis login --url ${env_url} --api-key <your-api-key>${NC}"
    echo ""
}

main "$@"
