#!/bin/bash

# LaunchFast MCP Server - Railway Deployment Script
# This script automates deployment to Railway

set -e  # Exit on error

echo "🚂 LaunchFast MCP - Railway Deployment"
echo "======================================="
echo ""

# Check if Railway CLI is installed
if ! command -v railway &> /dev/null; then
    echo "❌ Railway CLI not found!"
    echo "   Install: npm i -g @railway/cli"
    echo "   Then run: railway login"
    exit 1
fi

echo "✅ Railway CLI detected"

# Check if logged in
if ! railway whoami &> /dev/null; then
    echo "❌ Not logged in to Railway!"
    echo "   Run: railway login"
    exit 1
fi

echo "✅ Logged in as: $(railway whoami)"
echo ""

# Check for required environment variables
echo "🔍 Checking environment variables..."

VARS_MISSING=false

if ! railway variables | grep -q "LAUNCHFAST_API_URL"; then
    echo "❌ LAUNCHFAST_API_URL not set"
    VARS_MISSING=true
fi

if ! railway variables | grep -q "LAUNCHFAST_API_KEY"; then
    echo "❌ LAUNCHFAST_API_KEY not set"
    VARS_MISSING=true
fi

if ! railway variables | grep -q "LAUNCHFAST_USER_ID"; then
    echo "❌ LAUNCHFAST_USER_ID not set"
    VARS_MISSING=true
fi

if [ "$VARS_MISSING" = true ]; then
    echo ""
    echo "📋 Set environment variables with:"
    echo "   railway variables set LAUNCHFAST_API_URL=https://launchfastlegacyx.com"
    echo "   railway variables set LAUNCHFAST_API_KEY=lf_your_key_here"
    echo "   railway variables set LAUNCHFAST_USER_ID=your_user_id_here"
    echo "   railway variables set ALLOWED_ORIGINS=*"
    exit 1
fi

echo "✅ All environment variables set"
echo ""

# Build locally to catch errors early
echo "📦 Building locally..."
npm run build

if [ $? -ne 0 ]; then
    echo "❌ Build failed! Fix errors before deploying."
    exit 1
fi

echo "✅ Local build successful"
echo ""

# Check git status
if [[ -n $(git status -s) ]]; then
    echo "📝 Uncommitted changes detected"
    echo ""
    git status -s
    echo ""
    read -p "Commit changes? (y/n): " -n 1 -r
    echo ""
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        read -p "Commit message: " COMMIT_MSG
        git add .
        git commit -m "$COMMIT_MSG"
        echo "✅ Changes committed"
    else
        echo "⚠️  Deploying with uncommitted changes..."
    fi
fi

echo ""

# Deploy to Railway
echo "🚀 Deploying to Railway..."
echo ""

railway up

if [ $? -ne 0 ]; then
    echo "❌ Deployment failed!"
    echo "   Check logs: railway logs"
    exit 1
fi

echo ""
echo "✅ Deployment successful!"
echo ""

# Get deployment URL
echo "🌐 Getting deployment URL..."
DOMAIN=$(railway domain 2>&1 | grep -o 'https://[^[:space:]]*' || echo "")

if [ -z "$DOMAIN" ]; then
    echo "⚠️  Could not auto-detect domain"
    echo "   Run: railway domain"
else
    echo "📡 Your MCP Server URL:"
    echo "   $DOMAIN"
    echo ""

    # Test health endpoint
    echo "🏥 Testing health endpoint..."
    sleep 5  # Give server time to start

    HEALTH_RESPONSE=$(curl -s -w "\n%{http_code}" "$DOMAIN/health" || echo "000")
    HTTP_CODE=$(echo "$HEALTH_RESPONSE" | tail -1)
    BODY=$(echo "$HEALTH_RESPONSE" | head -n -1)

    if [ "$HTTP_CODE" = "200" ]; then
        echo "✅ Health check passed!"
        echo "$BODY" | python3 -m json.tool 2>/dev/null || echo "$BODY"
    else
        echo "⚠️  Health check failed (HTTP $HTTP_CODE)"
        echo "   This might be normal if the server is still starting"
        echo "   Check status: railway logs"
    fi

    echo ""
    echo "📋 Team Connection URL:"
    echo "   $DOMAIN/sse"
fi

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "✨ Deployment Complete!"
echo ""
echo "📖 Next Steps:"
echo "   1. Test: curl $DOMAIN/health"
echo "   2. View logs: railway logs"
echo "   3. Open dashboard: railway open"
echo "   4. Share connection info with team"
echo ""
echo "👥 Team Config:"
echo "   MCP_SERVER_URL: $DOMAIN/sse"
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
