#!/bin/bash
set -e
REPO_URL="https://github.com/budongchan/agentcast.git"
TARGET="$HOME/Documents/GitHub/agentcast"
PORT="8787"

echo "========================================"
echo " CastAgent + OpenClaw macOS 자동세팅"
echo "========================================"
xattr -dr com.apple.quarantine "$0" 2>/dev/null || true

need_cmd(){ command -v "$1" >/dev/null 2>&1; }

if ! need_cmd git; then
  echo "❌ Git이 필요합니다. Xcode Command Line Tools 설치창이 뜨면 설치 후 다시 실행하세요."
  xcode-select --install 2>/dev/null || true
  read -r -p "설치 후 Enter를 누르세요..."
fi

if ! need_cmd node || ! need_cmd npm; then
  echo "Node.js/npm이 없습니다. Homebrew로 설치를 시도합니다."
  if need_cmd brew; then
    brew install node
  else
    echo "❌ Homebrew가 없습니다. https://nodejs.org 에서 Node.js LTS 설치 후 다시 실행하세요."
    open "https://nodejs.org/" || true
    exit 1
  fi
fi

mkdir -p "$HOME/Documents/GitHub"
if [ -d "$TARGET/.git" ]; then
  cd "$TARGET" && git pull --rebase || true
else
  git clone "$REPO_URL" "$TARGET"
fi
cd "$TARGET"

echo "OpenClaw 설치/업데이트 중..."
npm install -g openclaw

mkdir -p "$HOME/.openclaw/workspace"
openclaw setup --non-interactive --workspace "$HOME/.openclaw/workspace" || true

read -r -p "BotFather에서 받은 Telegram 봇 토큰을 붙여넣으세요(없으면 Enter로 건너뜀): " BOT_TOKEN
if [ -n "$BOT_TOKEN" ]; then
  openclaw channels add --channel telegram --bot-token "$BOT_TOKEN" --account default || openclaw channels add --channel telegram --token "$BOT_TOKEN" --account default || true
fi

echo "Gateway 서비스 설치/시작 시도..."
openclaw gateway install || true
openclaw gateway start || true

echo "Google 연동은 브라우저 승인이 필요합니다."
read -r -p "지금 Google 연동을 시작할까요? (y/N): " DO_GOOGLE
if [[ "$DO_GOOGLE" =~ ^[Yy]$ ]]; then
  openclaw connect google || openclaw configure --section plugins || true
fi

echo "CastAgent 로컬 미리보기 실행: http://localhost:$PORT"
open "http://localhost:$PORT/ai-openclaw-telegram" || true
python3 -m http.server "$PORT"
