#!/usr/bin/env bash
# Build the manifest.json consumed by frontends/switcher/index.html.
# Scans frontends/<group>/NN-slug/ for an index.html and emits a JSON list.
# Read-only: it only reads the worktree and writes one JSON file.
set -euo pipefail

root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
out="$root/frontends/switcher/manifest.json"
mkdir -p "$(dirname "$out")"

tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT

# group dir -> label
declare -A LABEL=(
  [opus5]="Claude Opus 5"
  [sol]="GPT-5.6 Sol"
)

first=1
n=0
printf '[' > "$tmp"
for group in opus5 sol; do
  gdir="$root/frontends/$group"
  [[ -d "$gdir" ]] || continue
  for d in "$gdir"/*/; do
    [[ -f "${d}index.html" ]] || continue
    slug="$(basename "$d")"
    n=$((n+1))
    id="$(printf '%02d' "$n")"
    # title: prefer README first heading, else slug
    title="$slug"
    if [[ -f "${d}README.md" ]]; then
      t="$(awk '/^# /{sub(/^#+ */,""); print; exit}' "${d}README.md")"
      [[ -n "$t" ]] && title="$t"
    fi
    rel="frontends/$group/$slug/index.html"
    (( first )) || printf ',' >> "$tmp"
    first=0
    printf '{"id":"%s","title":%s,"path":"%s"}' \
      "$id" "$(python3 -c 'import json,sys;print(json.dumps(sys.argv[1]))' "$title")" "$rel" >> "$tmp"
  done
done
printf ']' >> "$tmp"

mv "$tmp" "$out"
echo "Wrote $out"
python3 - <<'PY'
import json,sys
d=json.load(open(sys.argv[1]))
print(f"{len(d)} frontends:")
for x in d:
    print(f"  [{x['group']}] {x['id']} {x['title']}  ->  {x['path']}")
PY
