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

# Usage: ./generate_obs_models_json.sh [OBS_DIR]
# Requires: jq

OBS_DIR=${1:-obs}

if ! command -v jq >/dev/null 2>&1; then
  echo "Error: jq is required. Install jq and retry." >&2
  exit 1
fi

[[ -d "$OBS_DIR" ]] || { echo "Error: directory '$OBS_DIR' not found" >&2; exit 1; }

# regions: top-level subdirs in OBS_DIR
mapfile -t REGIONS < <(find "$OBS_DIR" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort)

# obs = { region: region }
OBS_JSON=$(
  printf '%s\n' "${REGIONS[@]}" \
  | jq -Rn '[inputs | select(length>0)] | map({key:., value:.}) | from_entries'
)

# models = { region: { model: model } }
MODELS_JSON='{}'
for region in "${REGIONS[@]}"; do
  mapfile -t MODELS < <(find "$OBS_DIR/$region" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort)
  MAP_JSON=$(
    printf '%s\n' "${MODELS[@]}" \
    | jq -Rn '[inputs | select(length>0)] | map({key:., value:.}) | from_entries'
  )
  MODELS_JSON=$(jq -cn --arg region "$region" --argjson map "$MAP_JSON" --argjson acc "$MODELS_JSON" '$acc + {($region): $map}')
done

jq -n --argjson obs "$OBS_JSON" --argjson models "$MODELS_JSON" '{obs: $obs, models: $models}'
