#!/bin/zsh
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"

GREEN='%F{green}'
RED='%F{red}'
YELLOW='%F{yellow}'
BLUE='%F{blue}'
BOLD='%B'
NC='%b%f'

CONFIG_FILE="$HOME/.openclaw/openclaw.json"
GOLDEN_LOCAL="$HOME/.openclaw/golden-local.json"

clear
print -P "${BLUE}┌─────────────────────────────────────────────────────┐${NC}"
print -P "${BLUE}│ ${BOLD}🔄 K K → Mac 本地模型遷移工具${NC}${BLUE} │${NC}"
print -P "${BLUE}│ ═════════════════════════════════════════════════ │${NC}"

if pgrep -f "ollama serve" > /dev/null 2>&1; then
 print -P "${BLUE}│${NC} [$(date '+%H:%M:%S')] ${GREEN}✅ Ollama 核心引擎運行中${NC}"
else
 print -P "${BLUE}│${NC} [$(date '+%H:%M:%S')] ${YELLOW}⚠️ Ollama 未開機，正在為您喚醒...${NC}"
 open -a Ollama
 sleep 4
fi

if curl -sf http://127.0.0.1:11434/api/tags | grep -q "qwen2.5:3b"; then
 print -P "${BLUE}│${NC} [$(date '+%H:%M:%S')] ${GREEN}✅ qwen2.5:3b 模型已就緒${NC}"
else
 print -P "${BLUE}│${NC} [$(date '+%H:%M:%S')] ${RED}❌ 未偵測到模型，開始自動下載 (1.9GB)...${NC}"
 ollama pull qwen2.5:3b
fi

chflags nouchg "$CONFIG_FILE" 2>/dev/null
chmod 644 "$CONFIG_FILE" 2>/dev/null

if [ -f "$GOLDEN_LOCAL" ]; then
 cp "$GOLDEN_LOCAL" "$CONFIG_FILE"
 cp "$GOLDEN_LOCAL" "$HOME/.openclaw/kk-golden.json" 2>/dev/null
 print -P "${BLUE}│${NC} [$(date '+%H:%M:%S')] ${GREEN}⚙️ 成功導入 Mac 本地優先架構設定${NC}"
else
 print -P "${BLUE}│${NC} [$(date '+%H:%M:%S')] ${RED}❌ 找不到黃金備份，切換中止${NC}"
 exit 1
fi

chmod 444 "$CONFIG_FILE"
chflags uchg "$CONFIG_FILE"

openclaw gateway restart > /dev/null 2>&1
sleep 2

print -P "${BLUE}│${NC}"
print -P "${BLUE}│${NC} [$(date '+%H:%M:%S')] ${GREEN}${BOLD}🟢 優先權已成功切換至 Mac 本地 Qwen！${NC}"
print -P "${BLUE}│${NC} ${YELLOW}ℹ️ 極速容錯已啟動：本地若卡死，3秒內自動盲切 K K${NC}"
print -P "${BLUE}└─────────────────────────────────────────────────────┘${NC}"
echo ""

read "CONFIRM?按 Enter 離開並關閉視窗..."
osascript -e 'tell application "Terminal" to close first window' &
exit 0
