#!/bin/bash
# Update ports file from core_nest configuration
# Gathers ports from pawprint and amar .env files
#
# Usage: ./update-ports.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PORTS_FILE="$SCRIPT_DIR/ports"

# TODO: Make these configurable or auto-detect
CORE_NEST_ROOT="${CORE_NEST_ROOT:-/home/mariano/core_nest}"
PAWPRINT_ENV="$CORE_NEST_ROOT/pawprint/.env"
AMAR_ENV="$CORE_NEST_ROOT/amar/.env"

echo "=== Updating Core Nest Ports ==="
echo ""

# Backup existing ports file
if [ -f "$PORTS_FILE" ]; then
    cp "$PORTS_FILE" "$PORTS_FILE.bak"
    echo "  ✓ Backed up existing ports to ports.bak"
fi

# Start new ports file
cat > "$PORTS_FILE" <<'EOF'
# Core Nest Ports
# Auto-generated by update-ports.sh
# Format: one port per line
# Comments allowed with #

EOF

# Extract ports from amar .env
if [ -f "$AMAR_ENV" ]; then
    echo "  Reading amar ports..."
    echo "# Amar" >> "$PORTS_FILE"

    # Frontend port (default 3000)
    AMAR_FRONTEND_PORT=$(grep "^AMAR_FRONTEND_PORT=" "$AMAR_ENV" 2>/dev/null | cut -d'=' -f2 || echo "3000")
    echo "$AMAR_FRONTEND_PORT" >> "$PORTS_FILE"

    # Backend port (default 8000)
    AMAR_BACKEND_PORT=$(grep "^AMAR_BACKEND_PORT=" "$AMAR_ENV" 2>/dev/null | cut -d'=' -f2 || echo "8000")
    echo "$AMAR_BACKEND_PORT" >> "$PORTS_FILE"

    echo "  ✓ Added amar ports: $AMAR_FRONTEND_PORT, $AMAR_BACKEND_PORT"
else
    echo "  ⚠ Amar .env not found, using defaults"
    echo "# Amar (defaults)" >> "$PORTS_FILE"
    echo "3000" >> "$PORTS_FILE"
    echo "8000" >> "$PORTS_FILE"
fi

echo "" >> "$PORTS_FILE"

# Extract ports from pawprint .env
if [ -f "$PAWPRINT_ENV" ]; then
    echo "  Reading pawprint ports..."
    echo "# Pawprint Services" >> "$PORTS_FILE"

    PAWPRINT_PORT=$(grep "^PAWPRINT_PORT=" "$PAWPRINT_ENV" 2>/dev/null | cut -d'=' -f2 || echo "13000")
    ARTERY_PORT=$(grep "^ARTERY_PORT=" "$PAWPRINT_ENV" 2>/dev/null | cut -d'=' -f2 || echo "13001")
    ALBUM_PORT=$(grep "^ALBUM_PORT=" "$PAWPRINT_ENV" 2>/dev/null | cut -d'=' -f2 || echo "13002")
    WARD_PORT=$(grep "^WARD_PORT=" "$PAWPRINT_ENV" 2>/dev/null | cut -d'=' -f2 || echo "13003")

    echo "$PAWPRINT_PORT" >> "$PORTS_FILE"
    echo "$ARTERY_PORT" >> "$PORTS_FILE"
    echo "$ALBUM_PORT" >> "$PORTS_FILE"
    echo "$WARD_PORT" >> "$PORTS_FILE"

    echo "  ✓ Added pawprint ports: $PAWPRINT_PORT, $ARTERY_PORT, $ALBUM_PORT, $WARD_PORT"
else
    echo "  ⚠ Pawprint .env not found, using defaults"
    echo "# Pawprint Services (defaults)" >> "$PORTS_FILE"
    echo "13000" >> "$PORTS_FILE"
    echo "13001" >> "$PORTS_FILE"
    echo "13002" >> "$PORTS_FILE"
    echo "13003" >> "$PORTS_FILE"
fi

echo ""
echo "=== Done ==="
echo ""
echo "Updated ports file: $PORTS_FILE"
echo ""
cat "$PORTS_FILE"
