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

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
MANIFEST="${MANIFEST:-$REPO_ROOT/content/audio.yaml}"
OUT="${OUT:-$REPO_ROOT/web/src/lib/artists.json}"

for tool in yq jq; do
	if ! command -v "$tool" >/dev/null; then
		echo "error: $tool not in PATH (try: nix develop)" >&2
		exit 1
	fi
done

yq -o=json '.' "$MANIFEST" | jq '
	def render_artist:
		. as $a |
		{
			id: $a.id,
			name: $a.name,
			slug: $a.slug,
			description: ($a.description // "" | rtrimstr("\n")),
			images: [
				($a.images // []) | to_entries[] |
				("/images/" + $a.slug + "-" + ((.key + 1) | tostring) + ".webp")
			],
			shows: [
				$a.shows[] | . as $s | {
					caption: $s.caption,
					slug: $s.slug,
					sides: [
						$s.sides[] | {
							id: .id,
							label: .label,
							audio: ("/audio/" + $a.slug + "-" + $s.slug + "-" + .id + ".opus")
						}
					]
				}
			]
		};

	{
		exhibit: .exhibit,
		artists: [ .artists[] | render_artist ]
	}
' > "$OUT.tmp"

mv "$OUT.tmp" "$OUT"
echo "wrote $OUT ($(jq '.artists | length' "$OUT") artists)"
