#!/usr/bin/env bash
# Focused UI manifest smoke test. Normally called by
# smoke-test-backend-public-assets.sh.
set -euo pipefail

API_BASE="${1:-http://127.0.0.1:3000}"
TMP_DIR="$(mktemp -d)"
MANIFEST="$TMP_DIR/manifest.json"
FILES="$TMP_DIR/files.txt"

curl -fsS "$API_BASE/api/assets/ui/manifest.json?ts=$(date +%s)" \
  -H 'Cache-Control: no-cache' \
  -o "$MANIFEST" || {
    echo "ERROR: UI asset manifest request failed" >&2
    exit 1
  }

python3 - "$MANIFEST" "$FILES" <<'PY'
import json, sys

manifest_path, files_path = sys.argv[1], sys.argv[2]
m = json.load(open(manifest_path))

required_paths = [
    "coverFrame",
    "envelope",
    "quill",
    "postcardBack.digital",
    "postcardBack.physical",
]

def get(path):
    cur = m
    for part in path.split("."):
        if not isinstance(cur, dict) or part not in cur:
            return None
        cur = cur[part]
    return cur

missing = [p for p in required_paths if not get(p)]
if missing:
    print("ERROR: required UI manifest key(s) missing:")
    for p in missing:
        print(" -", p)
    sys.exit(1)

files = []

def collect(value):
    if isinstance(value, str):
        files.append(value)
    elif isinstance(value, dict):
        for v in value.values():
            collect(v)
    elif isinstance(value, list):
        for v in value:
            collect(v)

collect(m)

files = sorted(set(f for f in files if f))
open(files_path, "w").write("\n".join(files) + "\n")

PY

while IFS= read -r file; do
  code=$(curl -fsS -o /dev/null -w '%{http_code}' \
    "$API_BASE/api/assets/ui/$file?ts=$(date +%s)" \
    -H 'Cache-Control: no-cache' || true)

  if [ "$code" != "200" ]; then
    echo "ERROR: asset not served: $file HTTP $code"
    exit 1
  fi
done < "$FILES"

asset_count="$(wc -l < "$FILES" | tr -d '[:space:]')"
echo "  OK UI assets: $asset_count files"

