#!/usr/bin/env bash
# Start all DBIS Core services

set -euo pipefail

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

# Source utilities
source "$PROJECT_ROOT/dbis_core/scripts/utils/common.sh"

# Load configuration
load_config

log_info "========================================="
log_info "DBIS Core - Start Services"
log_info "========================================="
log_info ""

check_root
if ! command_exists pct; then
    error_exit "This script must be run on Proxmox host (pct command not found)"
fi

# Start containers in order
log_info "Starting containers..."

# Start PostgreSQL
if pct list | grep -q "^\s*${VMID_DBIS_POSTGRES_PRIMARY:-10100}\s"; then
    log_info "Starting PostgreSQL Primary..."
    pct start "${VMID_DBIS_POSTGRES_PRIMARY:-10100}" 2>/dev/null || log_warn "PostgreSQL may already be running"
    sleep 3
fi

# Start Redis
if pct list | grep -q "^\s*${VMID_DBIS_REDIS:-10120}\s"; then
    log_info "Starting Redis..."
    pct start "${VMID_DBIS_REDIS:-10120}" 2>/dev/null || log_warn "Redis may already be running"
    sleep 2
fi

# Start API
if pct list | grep -q "^\s*${VMID_DBIS_API_PRIMARY:-10150}\s"; then
    log_info "Starting API Primary..."
    pct start "${VMID_DBIS_API_PRIMARY:-10150}" 2>/dev/null || log_warn "API may already be running"
    sleep 3
fi

# Start Frontend
if pct list | grep -q "^\s*${VMID_DBIS_FRONTEND:-10130}\s"; then
    log_info "Starting Frontend..."
    pct start "${VMID_DBIS_FRONTEND:-10130}" 2>/dev/null || log_warn "Frontend may already be running"
    sleep 2
fi

log_info ""
log_info "Waiting for services to be ready..."
sleep 5

log_info ""
log_success "Services started!"
log_info ""
log_info "Run './scripts/management/status.sh' to check service status"

