#!/usr/bin/env bash

# Convert a staged JAXA fetch manifest into a local reviewable H3 snapshot.

set -euo pipefail

if [[ $# -gt 1 ]]; then
  echo "usage: $0 [cloud-atmosphere-data-directory]" >&2
  exit 2
fi

data_dir=${1:-assets.static/cloud-atmosphere}
profile="$data_dir/cloud-atmosphere-profile.json"
manifest="$data_dir/.raw/cloud-atmosphere-fetch-manifest.json"
prepared_dir="$data_dir/.prepared"
output="$prepared_dir/cloud-atmosphere-latest.geojson"
output_manifest="$prepared_dir/cloud-atmosphere-latest.manifest.json"
preparer=${CLOUD_ATMOSPHERE_PREPARER:-src.generate/prepare-cloud-atmosphere}
for path in "$profile" "$manifest"; do
  if [[ ! -f $path ]]; then
    echo "missing cloud-atmosphere preparation input: $path" >&2
    exit 1
  fi
done
if [[ ! -x $preparer ]]; then
  echo "missing preparer executable: $preparer" >&2
  exit 1
fi
# Recompute every staged raster digest before trusting the fetch manifest's
# provenance. Paths are relative to .raw and are generated by the fetcher.
jq -r '.observations[].files[] | "\(.sha256)  \(.path)"' "$manifest" \
  | (cd "$(dirname "$manifest")" && sha256sum -c -)
mkdir -p "$prepared_dir"
temporary=$(mktemp "$prepared_dir/cloud-atmosphere.XXXXXX.geojson")
trap 'rm -f "$temporary"' EXIT
"$preparer" "$profile" "$manifest" "$temporary"
mv -f "$temporary" "$output"
trap - EXIT
jq -n --arg snapshot "$(basename "$output")" \
  --arg sha256 "$(sha256sum "$output" | sed 's/[[:space:]].*//')" \
  --arg profile "$(basename "$profile")" \
  --arg fetch_manifest "$(realpath --relative-to="$prepared_dir" "$manifest")" \
  '{schema:"cartofreako-cloud-atmosphere-prepared-manifest-v1",
    snapshot:$snapshot,sha256:$sha256,profile:$profile,
    fetch_manifest:$fetch_manifest}' > "$output_manifest"
printf 'Prepared snapshot: %s\n' "$output"
printf 'Review layer coverage, ages, and missing-data regions before rendering.\n'
