#!/usr/bin/env bash
set -euo pipefail

usage() {
  cat <<'EOF'
Usage: tools/serve-web.sh [example] [--dev] [--port PORT]

Build the given roast2d example for the wasm32-unknown-unknown target and
serve the generated files via a local HTTP server (python3 -m http.server).

Environment variables:
  PROFILE  Build profile to use (default: release)
  PORT     Port to use for the dev server (default: 8080)

Examples:
  tools/serve-web.sh breakout
  PORT=9000 PROFILE=debug tools/serve-web.sh cube
EOF
}

example=""
profile="${PROFILE:-release}"
port="${PORT:-8080}"

while [[ $# -gt 0 ]]; do
  case "$1" in
    -h|--help)
      usage
      exit 0
      ;;
    --port)
      if [[ $# -lt 2 ]]; then
        echo "--port requires a value" >&2
        exit 1
      fi
      port="$2"
      shift 2
      ;;
    --dev)
      profile="debug"
      shift
      ;;
    --profile)
      if [[ $# -lt 2 ]]; then
        echo "--profile requires a value" >&2
        exit 1
      fi
      profile="$2"
      shift 2
      ;;
    --)
      shift
      break
      ;;
    -*)
      echo "Unknown option: $1" >&2
      exit 1
      ;;
    *)
      if [[ -n "$example" ]]; then
        echo "Multiple examples provided: '$example' and '$1'" >&2
        exit 1
      fi
      example="$1"
      shift
      ;;
  esac
done

if [[ -z "$example" ]]; then
  echo "No example specified; defaulting to 'breakout'" >&2
  example="breakout"
fi

if ! command -v wasm-bindgen >/dev/null 2>&1; then
  echo "wasm-bindgen CLI is required but not found in PATH" >&2
  echo "Install via 'cargo install wasm-bindgen-cli'" >&2
  exit 1
fi

profile_flag=()
profile_dir="$profile"
case "$profile" in
  release)
    profile_flag+=("--release")
    ;;
  debug)
    ;; # default cargo profile
  *)
    profile_flag+=("--profile" "$profile")
    ;;
esac

cargo build --target wasm32-unknown-unknown --example "$example" "${profile_flag[@]}"

case "$profile" in
  release) wasm_dir="release" ;;
  debug) wasm_dir="debug" ;;
  *) wasm_dir="$profile" ;;
esac

wasm_path="target/wasm32-unknown-unknown/${wasm_dir}/examples/${example}.wasm"
if [[ ! -f "$wasm_path" ]]; then
  echo "Expected wasm output not found at $wasm_path" >&2
  exit 1
fi

out_dir="target/web/${example}"
rm -rf "$out_dir"
mkdir -p "$out_dir"

wasm-bindgen "$wasm_path" --target web --no-typescript --out-dir "$out_dir" --out-name "$example"

cat >"$out_dir/index.html" <<EOF
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>${example} (roast2d wasm)</title>
    <style>
      html, body { margin: 0; padding: 0; width: 100%; height: 100%; background: #000; }
      canvas { width: 100%; height: 100%; display: block; }
    </style>
  </head>
  <body>
    <script type="module">
      import init from "./${example}.js";

      init().catch((err) => {
        console.error("Failed to load wasm module", err);
        const banner = document.createElement("div");
        banner.style.position = "fixed";
        banner.style.top = "0";
        banner.style.left = "0";
        banner.style.right = "0";
        banner.style.background = "#ff5555";
        banner.style.color = "#fff";
        banner.style.padding = "12px";
        banner.style.fontFamily = "monospace";
        banner.textContent = 'Unable to start example ${example}: ' + err;
        document.body.appendChild(banner);
      });
    </script>
  </body>
</html>
EOF

echo "Build complete. Serving ${example} from ${out_dir} on http://localhost:${port}/"
echo "Press Ctrl+C to stop."

exec python3 -m http.server "$port" --directory "$out_dir"
