#!/bin/bash
#
# AtlasOS - Calypso API Restart Script
# Rebuilds and restarts the API server
#

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"
}

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

# Check if server is running
if pgrep -f "calypso-api" > /dev/null; then
    log_warn "Stopping existing calypso-api process..."
    pkill -f "calypso-api" || true
    sleep 2
fi

log_info "Starting Calypso API..."
log_info "Server will start on http://localhost:8080"
log_info ""
log_info "To run in background:"
log_info "  nohup ./bin/calypso-api -config config.yaml.example > /var/log/calypso-api.log 2>&1 &"
log_info ""
log_info "Or run in foreground:"
log_info "  ./bin/calypso-api -config config.yaml.example"
log_info ""

# Check if environment variables are set
if [ -z "${CALYPSO_DB_PASSWORD:-}" ]; then
    log_warn "CALYPSO_DB_PASSWORD not set"
fi
if [ -z "${CALYPSO_JWT_SECRET:-}" ]; then
    log_warn "CALYPSO_JWT_SECRET not set"
fi

