#!/bin/bash
set -e

# Local development server for build.valuecurve.co
# Mirrors production: static files + API proxy

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
DIST_DIR="$PROJECT_DIR/dist"

# Configurable ports (can override with env vars)
CADDY_PORT=${CADDY_PORT:-8080}
API_PORT=${API_PORT:-8000}

if [ ! -d "$DIST_DIR" ]; then
    echo "Error: dist/ not found. Run ./scripts/build.sh first."
    exit 1
fi

# Generate Caddyfile dynamically (HTTP-only for local dev)
CADDYFILE=$(mktemp)
cat > "$CADDYFILE" << CADDY
{
    auto_https off
}

:$CADDY_PORT {
    root * "$DIST_DIR"
    
    handle /api/* {
        reverse_proxy localhost:$API_PORT
    }
    
    handle {
        try_files {path} {path}/ {path}/index.html /index.html
        file_server
    }
}
CADDY

echo "Starting local dev server..."
echo "  Static files: $DIST_DIR"
echo "  Caddy:        http://localhost:$CADDY_PORT"
echo "  API proxy:    localhost:$API_PORT"
echo ""
echo "Make sure backend is running on port $API_PORT"
echo "Press Ctrl+C to stop"
echo ""

caddy run --adapter caddyfile --config "$CADDYFILE"
