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

runtime_python="${CODEX_PRIMARY_RUNTIME_PYTHON:?CODEX_PRIMARY_RUNTIME_PYTHON is required}"
workspace_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

for year in "$@"; do
  zip_path="${workspace_root}/raw_cache/Nat${year}us.zip"
  output_path="${workspace_root}/analysis/aggregate_${year}.json"
  source_url="https://ftp.cdc.gov/pub/Health_Statistics/NCHS/Datasets/DVS/natality/Nat${year}us.zip"

  printf 'Downloading %s\n' "$year"
  curl -L --fail --retry 3 --continue-at - -o "$zip_path" "$source_url"
  unzip -t "$zip_path" >/dev/null

  printf 'Aggregating %s\n' "$year"
  "$runtime_python" "${workspace_root}/analysis/aggregate_natality.py" \
    --year "$year" \
    --zip "$zip_path" \
    --output "$output_path"

  test -s "$output_path"
  rm -f "$zip_path"
  printf 'Completed %s\n' "$year"
done
