#!/bin/sh
# ============================================
# OWEN CLI Installer
# https://github.com/fuwa-co/owen-cli
#
# Usage:
#   curl -fsSL https://get.owen.fuwa.co/install.sh | sh
#   wget -qO- https://get.owen.fuwa.co/install.sh | sh
#
# Or with a specific version:
#   curl -fsSL https://get.owen.fuwa.co/install.sh | sh -s -- --version 1.2.0
# ============================================

set -e

# ── Configuration ──
REPO="fuwa-co/owen-cli"
BINARY="owen"
INSTALL_DIR="/usr/local/bin"
GITHUB_API="https://api.github.com"

# ── Brand colors (ANSI) ──
AMBER='\033[38;2;245;158;11m'
GREEN='\033[38;2;34;197;94m'
RED='\033[38;2;239;68;68m'
SLATE='\033[38;2;148;163;184m'
WHITE='\033[38;2;248;250;252m'
BOLD='\033[1m'
RESET='\033[0m'

# ── Helpers ──
info()    { printf "${SLATE}  · %s${RESET}\n" "$1"; }
success() { printf "${GREEN}${BOLD}  ✓${RESET} %s\n" "$1"; }
error()   { printf "${RED}${BOLD}  ✗${RESET} %s\n" "$1"; exit 1; }

banner() {
    printf "\n"
    printf "${AMBER}${BOLD}  ╔═══════════════════════════════════════╗${RESET}\n"
    printf "${AMBER}${BOLD}  ║${RESET}${WHITE}  OWEN CLI Installer                   ${AMBER}${BOLD}║${RESET}\n"
    printf "${AMBER}${BOLD}  ║${RESET}${SLATE}  OpenClaw Workflow for ENterprise      ${AMBER}${BOLD}║${RESET}\n"
    printf "${AMBER}${BOLD}  ╚═══════════════════════════════════════╝${RESET}\n"
    printf "\n"
}

# ── Detect platform ──
detect_platform() {
    OS=$(uname -s | tr '[:upper:]' '[:lower:]')
    ARCH=$(uname -m)

    case "$OS" in
        darwin) OS="darwin" ;;
        linux)  OS="linux" ;;
        *)      error "Unsupported OS: $OS" ;;
    esac

    case "$ARCH" in
        x86_64|amd64)   ARCH="amd64" ;;
        arm64|aarch64)  ARCH="arm64" ;;
        *)              error "Unsupported architecture: $ARCH" ;;
    esac

    PLATFORM="${OS}-${ARCH}"
}

# ── Get latest version from GitHub ──
get_version() {
    if [ -n "$VERSION" ]; then
        return
    fi

    info "Checking latest version..."
    VERSION=$(curl -fsSL "${GITHUB_API}/repos/${REPO}/releases/latest" \
        | grep '"tag_name"' \
        | sed -E 's/.*"v?([^"]+)".*/\1/')

    if [ -z "$VERSION" ]; then
        error "Could not determine latest version"
    fi
}

# ── Download binary ──
download() {
    ASSET_NAME="${BINARY}-${PLATFORM}"
    DOWNLOAD_URL="https://github.com/${REPO}/releases/download/v${VERSION}/${ASSET_NAME}"

    info "Downloading owen v${VERSION} for ${PLATFORM}..."

    TMP_DIR=$(mktemp -d)
    TMP_FILE="${TMP_DIR}/${BINARY}"

    HTTP_CODE=$(curl -fsSL -w "%{http_code}" -o "$TMP_FILE" "$DOWNLOAD_URL" 2>/dev/null || true)

    if [ "$HTTP_CODE" != "200" ] && [ ! -s "$TMP_FILE" ]; then
        rm -rf "$TMP_DIR"
        error "Download failed (HTTP ${HTTP_CODE}). Check: ${DOWNLOAD_URL}"
    fi

    chmod +x "$TMP_FILE"
    success "Downloaded successfully"
}

# ── Install binary ──
install_binary() {
    info "Installing to ${INSTALL_DIR}/${BINARY}..."

    # Check if we need sudo
    if [ -w "$INSTALL_DIR" ]; then
        mv "$TMP_FILE" "${INSTALL_DIR}/${BINARY}"
    else
        info "Elevated permissions required for ${INSTALL_DIR}"
        sudo mv "$TMP_FILE" "${INSTALL_DIR}/${BINARY}"
        sudo chmod +x "${INSTALL_DIR}/${BINARY}"
    fi

    rm -rf "$TMP_DIR"
    success "Installed to ${INSTALL_DIR}/${BINARY}"
}

# ── Verify installation ──
verify() {
    if command -v "$BINARY" >/dev/null 2>&1; then
        INSTALLED_VERSION=$("$BINARY" version 2>/dev/null || echo "unknown")
        success "owen is ready (${INSTALLED_VERSION})"
    else
        error "Installation succeeded but '${BINARY}' not found in PATH"
    fi
}

# ── Parse arguments ──
parse_args() {
    while [ $# -gt 0 ]; do
        case "$1" in
            --version)  VERSION="$2"; shift 2 ;;
            --dir)      INSTALL_DIR="$2"; shift 2 ;;
            *)          shift ;;
        esac
    done
}

# ── Main ──
main() {
    parse_args "$@"
    banner
    detect_platform
    info "Detected platform: ${PLATFORM}"
    get_version
    download
    install_binary
    verify

    printf "\n"
    printf "${AMBER}  Next steps:${RESET}\n"
    printf "${WHITE}    owen install${RESET}     ${SLATE}— Run the setup wizard${RESET}\n"
    printf "${WHITE}    owen agents${RESET}      ${SLATE}— Browse the agent catalog${RESET}\n"
    printf "${WHITE}    owen help${RESET}        ${SLATE}— Full command reference${RESET}\n"
    printf "\n"
}

main "$@"
