#!/bin/bash
#
# AtlasOS - Calypso API Service Restart Script
# Restarts the API server using systemd service
#

set -euo pipefail

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    log_error "Please run as root (use sudo)"
    exit 1
fi

cd "$(dirname "$0")/../backend" || exit 1

log_info "Building Calypso API..."

# Build the application
if go build -o bin/calypso-api ./cmd/calypso-api; then
    log_info "✓ Build successful"
else
    log_error "✗ Build failed"
    exit 1
fi

# Restart the service
log_info "Restarting calypso-api service..."
if systemctl restart calypso-api; then
    log_info "✓ Service restarted successfully"
    sleep 2
    
    # Check service status
    if systemctl is-active --quiet calypso-api; then
        log_info "✓ Service is running"
        log_info ""
        log_info "Service Status:"
        systemctl status calypso-api --no-pager -l | head -15
        log_info ""
        log_info "Recent logs:"
        journalctl -u calypso-api --no-pager -n 10 | tail -5
    else
        log_error "✗ Service failed to start"
        log_error "Check logs with: sudo journalctl -u calypso-api -n 50"
        exit 1
    fi
else
    log_error "✗ Failed to restart service"
    exit 1
fi

log_info ""
log_info "✅ API server restarted successfully!"
log_info "   Health check: curl http://localhost:8080/api/v1/health"
log_info "   View logs: sudo journalctl -u calypso-api -f"

