#!/bin/bash

# Notion↔GitHub Sync System Setup Script
# This script sets up the sync system between Notion and GitHub

set -e

echo "🚀 Setting up Notion↔GitHub Sync System"
echo "========================================"

# Check for required tools
echo "🔍 Checking prerequisites..."
command -v node >/dev/null 2>&1 || { echo "❌ Node.js is required but not installed."; exit 1; }
command -v npm >/dev/null 2>&1 || { echo "❌ npm is required but not installed."; exit 1; }

# Check Node version
NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 18 ]; then
  echo "❌ Node.js 18 or higher is required. Current: $(node -v)"
  exit 1
fi

echo "✅ Node.js $(node -v) detected"

# Install dependencies
echo "📦 Installing dependencies..."
cd "$(dirname "$0")"
npm install

# Check for configuration
echo "🔧 Checking configuration..."
if [ ! -f "../../clawd-scripts/config.env" ]; then
  echo "❌ config.env not found in clawd-scripts directory"
  echo "Please ensure NOTION_API_KEY is configured in config.env"
  exit 1
fi

# Check for Notion API key
if ! grep -q "NOTION_API_KEY=" "../../clawd-scripts/config.env"; then
  echo "❌ NOTION_API_KEY not found in config.env"
  exit 1
fi

echo "✅ Notion API key found in config"

# Check for GitHub token
if [ -z "$GITHUB_TOKEN" ]; then
  echo "⚠️  GITHUB_TOKEN environment variable not set"
  echo "Please set it with: export GITHUB_TOKEN=your_github_token"
  echo "Or add it to your shell profile"
fi

# Create sync state file
echo "📁 Creating sync state file..."
SYNC_STATE="sync-state.json"
if [ ! -f "$SYNC_STATE" ]; then
  echo '{
    "lastSync": null,
    "syncedTasks": {},
    "syncedLogs": {},
    "syncedLogEntries": {},
    "lastLogHash": null
  }' > "$SYNC_STATE"
  echo "✅ Created $SYNC_STATE"
else
  echo "✅ $SYNC_STATE already exists"
fi

# Make scripts executable
echo "🔧 Making scripts executable..."
chmod +x *.js

# Create environment file template
echo "📝 Creating environment file template..."
ENV_TEMPLATE=".env.template"
if [ ! -f "$ENV_TEMPLATE" ]; then
  cat > "$ENV_TEMPLATE" << 'EOF'
# GitHub Configuration
GITHUB_TOKEN=your_github_personal_access_token_here
GITHUB_OWNER=rateright-growth
GITHUB_REPO=rateright-growth

# Sync Settings
DRY_RUN=false
SYNC_INTERVAL_MINUTES=15

# Notion Database IDs (override if needed)
# WORK_TRACKER_DB=your_database_id
# DEPLOY_LOG_DB=your_database_id
# AI_AGENTS_DB=your_database_id
# SYSTEM_STATE_DB=your_database_id
# LESSONS_LEARNED_DB=your_database_id
EOF
  echo "✅ Created $ENV_TEMPLATE"
  echo "   Please copy to .env and fill in your values"
fi

# Create .env file if it doesn't exist
if [ ! -f ".env" ]; then
  echo "📄 Creating .env file from template..."
  cp "$ENV_TEMPLATE" .env
  echo "✅ Created .env file"
  echo "   Please edit .env and add your GitHub token"
fi

# Test configuration
echo "🧪 Testing configuration..."
if node -e "const config = require('./config.js'); console.log('✅ Config loaded successfully'); console.log('   Notion DBs:', Object.keys(config.notion.databases).filter(k => config.notion.databases[k]).length);" 2>/dev/null; then
  echo "✅ Configuration test passed"
else
  echo "❌ Configuration test failed"
  exit 1
fi

echo ""
echo "========================================"
echo "✅ Setup completed successfully!"
echo ""
echo "📋 Next steps:"
echo "1. Edit .env file and add your GITHUB_TOKEN"
echo "2. Test the sync system: npm run sync-notion-to-github"
echo "3. Set up a cron job for automatic syncs"
echo ""
echo "🔄 Available commands:"
echo "   npm run sync-notion-to-github    # Sync Notion → GitHub"
echo "   npm run sync-github-to-notion    # Sync GitHub → Notion"
echo "   npm run sync-founder-log         # Sync FOUNDER-LOG.md"
echo "   npm run run-all                  # Run all syncs"
echo ""
echo "⏰ Example cron job (runs every 15 minutes):"
echo "   */15 * * * * cd /home/ccuser/rateright-growth/scripts/notion-github-sync && npm run run-all >> sync.log 2>&1"
echo ""
echo "📚 For more details, see README.md"