#!/bin/bash
# Optima Ops CLI 安装脚本
# 用法: curl -sSL https://raw.githubusercontent.com/Optima-Chat/optima-ops-cli-rust/main/scripts/install.sh | bash

set -e

VERSION="${1:-latest}"
INSTALL_DIR="${INSTALL_DIR:-/usr/local/bin}"

# 颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

echo -e "${CYAN}"
echo "   ____        _   _                    ____  "
echo "  / __ \      | | (_)                  / __ \ "
echo " | |  | |_ __ | |_ _ _ __ ___   __ _  | |  | |_ __  ___"
echo " | |  | | '_ \| __| | '_ \` _ \ / _\` | | |  | | '_ \/ __|"
echo " | |__| | |_) | |_| | | | | | | (_| | | |__| | |_) \__ \\"
echo "  \____/| .__/ \__|_|_| |_| |_|\__,_|  \____/| .__/|___/"
echo "        | |                                   | |       "
echo "        |_|                                   |_|       "
echo -e "${NC}"
echo ""

# 检测操作系统和架构
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)

case "$OS" in
    linux)
        case "$ARCH" in
            x86_64)
                PLATFORM="linux-x86_64"
                ;;
            *)
                echo -e "${RED}不支持的架构: $ARCH${NC}"
                exit 1
                ;;
        esac
        ;;
    darwin)
        case "$ARCH" in
            x86_64)
                PLATFORM="darwin-x86_64"
                ;;
            arm64)
                PLATFORM="darwin-arm64"
                ;;
            *)
                echo -e "${RED}不支持的架构: $ARCH${NC}"
                exit 1
                ;;
        esac
        ;;
    *)
        echo -e "${RED}不支持的操作系统: $OS${NC}"
        exit 1
        ;;
esac

echo -e "${GREEN}检测到系统: ${NC}$OS ($ARCH)"
echo -e "${GREEN}目标平台: ${NC}$PLATFORM"
echo ""

# 获取最新版本
if [ "$VERSION" = "latest" ]; then
    echo -e "${YELLOW}获取最新版本...${NC}"
    VERSION=$(curl -s https://api.github.com/repos/Optima-Chat/optima-ops-cli-rust/releases/latest | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
    if [ -z "$VERSION" ]; then
        echo -e "${RED}无法获取最新版本${NC}"
        exit 1
    fi
fi

echo -e "${GREEN}版本: ${NC}$VERSION"
echo ""

# 下载
DOWNLOAD_URL="https://github.com/Optima-Chat/optima-ops-cli-rust/releases/download/${VERSION}/oor-${PLATFORM}.tar.gz"
TEMP_DIR=$(mktemp -d)

echo -e "${YELLOW}下载中...${NC}"
echo "  $DOWNLOAD_URL"
curl -sL "$DOWNLOAD_URL" -o "$TEMP_DIR/oor.tar.gz"

# 解压
echo -e "${YELLOW}解压中...${NC}"
tar -xzf "$TEMP_DIR/oor.tar.gz" -C "$TEMP_DIR"

# 安装
echo -e "${YELLOW}安装到 $INSTALL_DIR ...${NC}"
if [ -w "$INSTALL_DIR" ]; then
    mv "$TEMP_DIR/oor" "$INSTALL_DIR/"
else
    sudo mv "$TEMP_DIR/oor" "$INSTALL_DIR/"
fi
chmod +x "$INSTALL_DIR/oor"

# 清理
rm -rf "$TEMP_DIR"

# 验证
if command -v oor &> /dev/null; then
    echo ""
    echo -e "${GREEN}安装成功!${NC}"
    echo ""
    oor --version
    echo ""
    echo -e "${CYAN}下一步:${NC}"
    echo "  1. 确保已配置 AWS CLI: aws configure"
    echo "  2. 运行初始化: oor init"
    echo "  3. 开始使用: oor --help"
else
    echo -e "${RED}安装失败${NC}"
    exit 1
fi
