#!/bin/bash
# Permanent Start Script for TechZone Application
# This script starts both backend and frontend with PM2 for auto-restart

set -e

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$SCRIPT_DIR"

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo "╔════════════════════════════════════════════════════════╗"
echo "║       TechZone Application - PM2 Startup               ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""

# Create logs directory
mkdir -p logs

# Check if PM2 is installed
if ! command -v pm2 &> /dev/null; then
    echo -e "${RED}✗ PM2 is not installed${NC}"
    echo "Installing PM2 globally..."
    npm install -g pm2
fi

echo -e "${GREEN}✓${NC} PM2 found: $(pm2 --version)"
echo ""

# Stop existing processes if running
echo "🔄 Stopping any existing processes..."
pm2 delete techzone-backend techzone-frontend 2>/dev/null || true
echo ""

# Kill any manual processes on the ports
echo "🔄 Cleaning up manual processes..."
pkill -f "uvicorn.*8181" || true
pkill -f "@craco/craco.*start" || true
pkill -f "node.*5300" || true
sleep 2

# Start with PM2
echo "🚀 Starting applications with PM2..."
pm2 start ecosystem.config.json

echo ""
echo "⏳ Waiting for applications to initialize..."
sleep 5

echo ""
echo "╔════════════════════════════════════════════════════════╗"
echo "║              Application Status                        ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""

pm2 status

echo ""
echo "╔════════════════════════════════════════════════════════╗"
echo "║              Quick Commands                            ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""
echo "View logs:"
echo "  pm2 logs techzone-backend    # Backend logs"
echo "  pm2 logs techzone-frontend   # Frontend logs"
echo "  pm2 logs                     # All logs"
echo ""
echo "Restart services:"
echo "  pm2 restart techzone-backend"
echo "  pm2 restart techzone-frontend"
echo "  pm2 restart all"
echo ""
echo "Stop services:"
echo "  pm2 stop techzone-backend"
echo "  pm2 stop techzone-frontend"
echo "  pm2 stop all"
echo ""
echo "Monitor services:"
echo "  pm2 monit                    # Real-time monitoring"
echo ""
echo "╔════════════════════════════════════════════════════════╗"
echo "║              Access URLs                               ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""
echo -e "${GREEN}Frontend:${NC} http://localhost:5300"
echo -e "${GREEN}Backend:${NC}  http://localhost:8181"
echo -e "${GREEN}API:${NC}      http://localhost:8181/api"
echo -e "${GREEN}Health:${NC}   http://localhost:8181/api/health"
echo ""

# Wait a bit more and test connectivity
sleep 10

echo "🔍 Testing connectivity..."
BACKEND_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8181/api/health 2>/dev/null || echo "000")
FRONTEND_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:5300 2>/dev/null || echo "000")

if [ "$BACKEND_STATUS" = "200" ]; then
    echo -e "${GREEN}✓${NC} Backend is responding (HTTP $BACKEND_STATUS)"
else
    echo -e "${YELLOW}⚠${NC} Backend not ready yet (HTTP $BACKEND_STATUS) - check logs: pm2 logs techzone-backend"
fi

if [ "$FRONTEND_STATUS" = "200" ]; then
    echo -e "${GREEN}✓${NC} Frontend is responding (HTTP $FRONTEND_STATUS)"
else
    echo -e "${YELLOW}⚠${NC} Frontend not ready yet (HTTP $FRONTEND_STATUS) - may take 20-30s to compile"
fi

echo ""
echo -e "${GREEN}🎉 Applications started with PM2!${NC}"
echo "Services will auto-restart if they crash."
echo ""
echo "To save PM2 configuration for system reboot:"
echo "  pm2 save"
echo "  pm2 startup"
echo ""
