#!/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}'
NC='%f'

CURRENT_TIME=$(date "+%H:%M:%S")
LOG_FILE="$HOME/.openclaw/logs/kk-recovery.log"
GOLDEN_CONFIG="$HOME/.openclaw/kk-golden.json"
CURRENT_CONFIG="$HOME/.openclaw/openclaw.json"

mkdir -p "$HOME/.openclaw/logs"

clear
print -P "${BLUE}┌─────────────────────────────────────────────────────┐${NC}"
print -P "${BLUE}│ 🔍 K K 智慧巡檢與恢復工具                          │${NC}"
print -P "${BLUE}│ ═════════════════════════════════════════════════ │${NC}"

NEED_FIX=0

PORT_CHECK=$(netstat -an | grep 18789 | grep LISTEN)
if [ -n "$PORT_CHECK" ]; then
  print -P "${BLUE}│${NC} [$CURRENT_TIME] ${GREEN}✅ Gateway port 18789 正常${NC}"
else
  print -P "${BLUE}│${NC} [$CURRENT_TIME] ${RED}❌ Gateway port 18789 斷線${NC}"
  NEED_FIX=1
fi

if [ -f "$CURRENT_CONFIG" ]; then
  GEMINI_CHECK=$(grep -i "gemini" "$CURRENT_CONFIG")
  PRIMARY_CHECK=$(grep "deepseek/deepseek-v4-flash" "$CURRENT_CONFIG")
  if [ -n "$PRIMARY_CHECK" ] && [ -z "$GEMINI_CHECK" ]; then
    print -P "${BLUE}│${NC} [$CURRENT_TIME] ${GREEN}✅ Primary: deepseek/deepseek-v4-flash${NC}"
    print -P "${BLUE}│${NC} [$CURRENT_TIME] ${GREEN}✅ 無 Gemini 污染${NC}"
  else
    print -P "${BLUE}│${NC} [$CURRENT_TIME] ${RED}❌ 設定檔異常或 Gemini 污染${NC}"
    NEED_FIX=1
  fi
else
  print -P "${BLUE}│${NC} [$CURRENT_TIME] ${RED}❌ 設定檔遺失${NC}"
  NEED_FIX=1
fi

if [ $NEED_FIX -eq 0 ]; then
  print -P "${BLUE}│${NC}"
  print -P "${BLUE}│${NC} [$CURRENT_TIME] ${GREEN}🟢 一切正常！DeepSeek KK 線路暢通無阻。${NC}"
  echo "[$(date)] 🟢 桌面巡檢：一切健康。" >> "$LOG_FILE"
else
  print -P "${BLUE}│${NC}"
  print -P "${BLUE}│${NC} [$CURRENT_TIME] ${YELLOW}⚠️ 啟動鐵腕修復流程...${NC}"
  echo "[$(date)] 🚨 桌面巡檢：偵測異常，啟動修復。" >> "$LOG_FILE"

  chflags nouchg "$CURRENT_CONFIG" 2>/dev/null
  chmod 644 "$CURRENT_CONFIG" 2>/dev/null
  rm -f "$HOME/.openclaw/.lock" 2>/dev/null
  find "$HOME/.openclaw" -maxdepth 1 -name '*.tmp' -delete 2>/dev/null

  if [ -f "$GOLDEN_CONFIG" ]; then
    cp "$GOLDEN_CONFIG" "$CURRENT_CONFIG"
    print -P "${BLUE}│${NC} [$CURRENT_TIME] ${GREEN}🛠️ 已從黃金備份還原${NC}"
  else
    echo '{"models":{"providers":{}},"agents":{"defaults":{"workspace":"/Users/lingochen/.openclaw/workspace","models":{"deepseek/deepseek-v4-flash":{}},"model":{"primary":"deepseek/deepseek-v4-flash","fallbacks":["deepseek/deepseek-v4-flash"]},"thinkingDefault":"off"},"list":[]}}' > "$CURRENT_CONFIG"
    print -P "${BLUE}│${NC} [$CURRENT_TIME] ${GREEN}🛠️ 已強行寫入標準 DeepSeek 結構${NC}"
  fi

  chmod 444 "$CURRENT_CONFIG"
  chflags uchg "$CURRENT_CONFIG"

  print -P "${BLUE}│${NC} [$CURRENT_TIME] ${YELLOW}🔄 正在重啟 Gateway...${NC}"
  openclaw gateway restart >> "$LOG_FILE" 2>&1
  sleep 3
  print -P "${BLUE}│${NC} [$CURRENT_TIME] ${GREEN}✅ 重啟完畢！${NC}"
fi

print -P "${BLUE}│${NC}"
print -P "${BLUE}└─────────────────────────────────────────────────────┘${NC}"
echo ""
read "CONFIRM?按 Enter 離開..."
osascript -e 'tell application "Terminal" to close first window' &
exit 0
