#!/bin/bash

# 切換模型 → siliconflow/deepseek-ai/DeepSeek-V4-Flash
# 雙擊 .command 直接執行，3 秒後自動關閉

echo "===================================="
echo "  切換模型 → SiliconFlow DeepSeek V4 Flash"
echo "===================================="
echo ""

# ── 1. 偵測 Gateway ──────────────────────────────────────
PORT="${OPENCLAW_GATEWAY_PORT:-18789}"
GW_URL="http://127.0.0.1:${PORT}"

echo "🔍 Gateway: ${GW_URL}"

OPENCLAW_PATH="$(command -v openclaw)"
if [ -n "$OPENCLAW_PATH" ]; then
    echo "✅ openclaw CLI: ${OPENCLAW_PATH}"
    echo "   版本: $($OPENCLAW_PATH --version 2>/dev/null | head -1)"
else
    echo "⚠️  找不到 openclaw CLI (但仍可能透過 curl 運作)"
fi
echo ""

# ── 2. 取得目前模型 ──────────────────────────────────────
echo "📌 目前 session 模型:"
if [ -n "$OPENCLAW_PATH" ]; then
    STATUS=$("$OPENCLAW_PATH" status 2>&1)
    echo "$STATUS" | grep -Ei "model" | head -3
fi
echo ""

# ── 3. 切換 session 模型 ─────────────────────────────────
echo "🔄 切換 session → siliconflow/deepseek-ai/DeepSeek-V4-Flash ..."

RESPONSE=$(curl -s -X POST "${GW_URL}/v1/sessions/agent:main:main" \
        -H "Content-Type: application/json" \
        -d '{"model":"siliconflow/deepseek-ai/DeepSeek-V4-Flash"}' \
        --max-time 10 2>&1)

if echo "$RESPONSE" | grep -qqi 'ok\|model'; then
    echo "✅ Session 切換成功!"
else
    echo "⚠️  Session API 回應: ${RESPONSE:0:200}"
    echo "   (沒關係，已嘗試切換)"
fi
echo ""

# ── 4. 確認新模型 ────────────────────────────────────────
echo "📌 新 session 模型:"
if [ -n "$OPENCLAW_PATH" ]; then
    "$OPENCLAW_PATH" status 2>&1 | grep -Ei "model" | head -3
fi
echo ""

echo "===================================="
echo "  ✨ 完成！3 秒後關閉"
echo "===================================="
sleep 3

# 自動關 Terminal
osascript -e 'tell application "Terminal" to close (every window whose custom title is "切換到SiliconFlow.command")' 2>/dev/null \
|| osascript -e 'tell application "Terminal" to close first window' 2>/dev/null \
|| true

exit 0