#!/bin/bash

# PHI|OS Services Start Script
# Starts the PHI|OS web application and related services

set -e

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

echo -e "${YELLOW}[PHI|OS] Starting services...${NC}"

# Check if we have the webapp
if [ ! -d "/rhiz/factory/hypergraph_meta_cluster_bundle/services/webapp" ]; then
    echo -e "${RED}[ERROR] PHI|OS webapp directory not found${NC}"
    exit 1
fi

cd /rhiz/factory/hypergraph_meta_cluster_bundle/services/webapp

# Check if package.json exists
if [ ! -f "package.json" ]; then
    echo -e "${RED}[ERROR] package.json not found in webapp directory${NC}"
    exit 1
fi

# Install dependencies if needed
echo -e "${YELLOW}[PHI|OS] Checking dependencies...${NC}"
if [ ! -d "node_modules" ]; then
    echo -e "${YELLOW}[PHI|OS] Installing npm dependencies...${NC}"
    npm install
    echo -e "${GREEN}[PHI|OS] Dependencies installed${NC}"
fi

# Build the application
echo -e "${YELLOW}[PHI|OS] Building application...${NC}"
npm run build
echo -e "${GREEN}[PHI|OS] Application built${NC}"

# Start the application
echo -e "${YELLOW}[PHI|OS] Starting web application...${NC}"
npm run start &
echo -e "${GREEN}[PHI|OS] Web application started${NC}"

# Check if the application is running
sleep 5
if ps aux | grep -v grep | grep "node.*webapp" > /dev/null; then
    echo -e "${GREEN}[PHI|OS] Application is running${NC}"
else
    echo -e "${RED}[ERROR] Application failed to start${NC}"
    exit 1
fi

# Run PHI|OS system genesis if available
echo -e "${YELLOW}[PHI|OS] Checking for system genesis...${NC}"
if [ -f "/rhiz/PHI|OS/genesis/phi-os-genesis.sh" ]; then
    echo -e "${YELLOW}[PHI|OS] Running system genesis...${NC}"
    cd /rhiz/PHI|OS
    chmod +x genesis/phi-os-genesis.sh
    ./genesis/phi-os-genesis.sh
    echo -e "${GREEN}[PHI|OS] System genesis completed${NC}"
else
    echo -e "${YELLOW}[PHI|OS] No genesis script found, skipping${NC}"
fi

echo -e "${GREEN}"
echo -e "╔════════════════════════════════════════════════════════════╗"
echo -e "║        PHI|OS Services Started Successfully               ║"
echo -e "║                                                           ║"
echo -e "║  Web Application: Running on port 3000                    ║"
echo -e "║  API Endpoint: http://localhost:3001/api/                 ║"
echo -e "║  WebSocket: http://localhost:3001/ws/                    ║"
echo -e "║  Web Root: /rhiz/PHI|OS/app/web                           ║"
echo -e "║                                                           ║"
echo -e "║  Access the application through your nginx proxy:       ║"
echo -e "║  http://uniphil.ch or https://uniphil.ch                 ║"
echo -e "║                                                           ║"
echo -e "╚════════════════════════════════════════════════════════════╝"
echo -e "${NC}"

exit 0
