#!/bin/bash
set -e
echo "🪄 Hermes 新手入門包 — 一鍵安裝"
echo "================================"
echo ""

# Check & install Python if needed
if ! command -v python3 &>/dev/null; then
    echo "📦 安裝 Python 3（Hermes 需要它）..."
    if [[ "$OSTYPE" == "darwin"* ]]; then
        # macOS
        if command -v brew &>/dev/null; then
            brew install python3
        else
            echo "❌ 請先安裝 Homebrew："
            echo "   /bin/bash -c \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""
            echo "   裝完再執行一次本腳本"
            exit 1
        fi
    elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
        sudo -S -p '' apt update && sudo -S -p '' apt install -y python3 python3-pip
    else
        echo "❌ 請手動安裝 Python 3：https://www.python.org/downloads/"
        exit 1
    fi
fi
echo "✅ Python $(python3 --version)"

# Ensure pip
if ! command -v pip3 &>/dev/null; then
    python3 -m ensurepip --upgrade 2>/dev/null || true
fi

# Install Hermes
echo ""
echo "📦 安裝 Hermes Agent..."
pip3 install hermes-agent --quiet 2>/dev/null || pip3 install hermes-agent --user --quiet
echo "✅ Hermes 安裝完成"

# Setup Hermes
echo ""
echo "⚙ 初始化設定..."
~/.local/bin/hermes setup --non-interactive 2>/dev/null || python3 -m hermes_cli.main setup --non-interactive 2>/dev/null || echo "⚠ 請手動執行 hermes setup"

# Download starter pack
echo ""
echo "📋 套用新手入門包..."
STARTER_DIR="$HOME/.hermes"
mkdir -p "$STARTER_DIR"/{skills,personas,cron}

TMPDIR=$(mktemp -d)
curl -fsSL "https://github.com/anthonytsai68/hermes-starter-pack/archive/refs/heads/main.zip" -o "$TMPDIR/starter.zip"
unzip -qo "$TMPDIR/starter.zip" -d "$TMPDIR"
cp "$TMPDIR/hermes-starter-pack-main/config/config.yaml" "$STARTER_DIR/" 2>/dev/null || true
cp -r "$TMPDIR/hermes-starter-pack-main/skills/"* "$STARTER_DIR/skills/" 2>/dev/null || true
cp -r "$TMPDIR/hermes-starter-pack-main/personas/"* "$STARTER_DIR/personas/" 2>/dev/null || true
cp -r "$TMPDIR/hermes-starter-pack-main/cron/"* "$STARTER_DIR/cron/" 2>/dev/null || true
rm -rf "$TMPDIR"
echo "✅ 入門包已安裝"

# API key reminder
echo ""
echo "🔑 下一步：買 Token 串上"
echo "   1. 到 https://platform.deepseek.com 註冊（支付寶/微信/信用卡都能儲值）"
echo "   2. 左邊「API Keys」→ 建立新 key → 複製 sk-xxxxxxxx"
echo "   3. 終端機執行：hermes model"
echo "   4. 選 DeepSeek → 貼上你的 key"
echo ""
echo "💡 DeepSeek V4 Pro：每百萬 token 只要 \$0.44/\$0.87"
echo "   一天對話花不到台幣 5 塊"
echo ""
echo "🎉 完成！打開 Hermes Desktop App 或執行 hermes chat"
echo "📖 更多說明：https://hermes.wow.to"
