#!/usr/bin/env bash
# Copyright 2026 ddbsh reimplementation contributors.
# SPDX-License-Identifier: Apache-2.0
#
# devtools/serve-web — build the browser edition (if needed) and serve the
# static bundle on THIS machine for hand-testing (P9).
#
# The bundle (build-preset/wasm-release/web/) is plain static files: index.html,
# the JS modules, ddbsh.wasm and the vendored AWS SDK bundle. WASM + ES modules
# do not load from file://, so it must be served over HTTP. Python's
# http.server sends `application/wasm` for .wasm (Python >= 3.8), and no
# cross-origin-isolation headers are needed (Asyncify, no threads).
#
# Binding: loopback ONLY (127.0.0.1), not configurable (D-P9-02-12). The page
# accepts credentials only in a secure context, and http://localhost is one;
# plain HTTP on a LAN address is not (and is where the page refuses
# credentials). To use the page from another machine, tunnel:
#   ssh -L 8080:localhost:8080 <this-host>     then open http://localhost:8080/
# For a hosted deployment (HTTPS, CSP response header), see
# docs/configurations/03-browser-aws.md.
#
# Usage:
#   devtools/serve-web [PORT]      # default port 8080; Ctrl-C stops the server
# Env overrides: devtools/lib-web.sh's (EMSDK, EMSDK_PYTHON, DDBSH_WASM_BUILD_DIR).

set -euo pipefail

PORT="${1:-8080}"
REPO_DIR="$(cd "$(dirname "$0")/.." && pwd)"
WASM_BUILD="${DDBSH_WASM_BUILD_DIR:-$REPO_DIR/build-preset/wasm-release}"
WEB_OUT="$WASM_BUILD/web"

if [ ! -f "$WEB_OUT/ddbsh.js" ] || [ ! -f "$WEB_OUT/index.html" ]; then
    echo "web bundle not found at $WEB_OUT — building via emcmake ..."
    # shellcheck source=devtools/lib-web.sh
    . "$REPO_DIR/devtools/lib-web.sh"
    web_setup_emsdk
    web_build_bundle "$REPO_DIR"
fi

echo "Serving $WEB_OUT at http://localhost:$PORT/ (bind 127.0.0.1, loopback only; Ctrl-C to stop)"
cd "$WEB_OUT"
exec python3 -m http.server --bind 127.0.0.1 "$PORT"
