#!/bin/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/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 custom base URL:
#   ./installer.sh --base-url http://alex.artemis.turintech.ai

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/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

# Custom base URL (optional)
BASE_URL_CUSTOM=""

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --version)
            VERSION="$2"
            shift 2
            ;;
        --dev)
            DEV=true
            shift
            ;;
        --nightly)
            NIGHTLY=true
            shift
            ;;
        --env)
            # Deprecated: environments no longer exist. dev maps to the
            # rolling dev build; stg/prod map to the newest release.
            if [ "$2" = "dev" ]; then
                DEV=true
            fi
            shift 2
            ;;
        --install-dir)
            INSTALL_DIR="$2"
            shift 2
            ;;
        --base-url)
            BASE_URL_CUSTOM="$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 "  --base-url <url>        Custom base URL for API endpoints"
            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"
            echo "  $0 --version 1.2.0                              # Specific release"
            echo "  $0 --dev                                        # Development build"
            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 config set ARTEMIS_API_KEY <your-api-key>   Set your API key"
        echo "  artemis --help         Show available commands"
        echo "  artemis status         Check configuration status"
        echo "  artemis config         Verify configuration"
    else
        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
}

# Configure environment-specific defaults
configure_environment() {
    # If custom base URL is provided, use it
    if [ -n "$BASE_URL_CUSTOM" ]; then
        echo -e "${BLUE}Configuring custom environment: ${BASE_URL_CUSTOM}${NC}"

        # Remove trailing slash if present
        BASE_URL_CUSTOM="${BASE_URL_CUSTOM%/}"

        "${BINARY_NAME}" config env "$BASE_URL_CUSTOM"

        echo -e "${GREEN}Environment configured for ${BASE_URL_CUSTOM}!${NC}"
    else
        echo -e "${BLUE}Configuring ${ENV} environment defaults...${NC}"

        # Use the config env command with predefined environments
        "${BINARY_NAME}" config env "$ENV"

        echo -e "${GREEN}Environment configured for ${ENV}!${NC}"
    fi

    echo -e "${YELLOW}Note: Set your API key with: artemis config set ARTEMIS_API_KEY <your-api-key>${NC}"
    echo ""
}

main "$@"
