#!/usr/bin/env bash

set -euo pipefail

repo_root="$(git rev-parse --show-toplevel)"
cd "$repo_root"

echo "[check-metadata] validating README workflow badge targets..."
mapfile -t badge_workflows < <(
  grep -oE 'actions/workflows/[^/]+\.yml/badge\.svg' README.md \
    | sed -E 's#actions/workflows/([^/]+)\.yml/badge\.svg#\1.yml#' \
    | sort -u
)

if [[ ${#badge_workflows[@]} -eq 0 ]]; then
  echo "No workflow badge URLs found in README.md"
  exit 1
fi

for workflow_file in "${badge_workflows[@]}"; do
  if [[ ! -f ".github/workflows/${workflow_file}" ]]; then
    echo "README badge references missing workflow file: .github/workflows/${workflow_file}"
    exit 1
  fi
done

echo "[check-metadata] validating CITATION version/date..."
project_version="$(sed -rn 's/  VERSION ([0-9]+\.[0-9]+\.[0-9]+)/\1/p' CMakeLists.txt | head -n1)"
citation_version="$(sed -rn 's/version: v([0-9]+\.[0-9]+\.[0-9]+)/\1/p' CITATION.cff | head -n1)"

if [[ -z "$project_version" || -z "$citation_version" ]]; then
  echo "Unable to parse project/citation versions"
  exit 1
fi

if [[ "$project_version" != "$citation_version" ]]; then
  echo "CITATION.cff version (v${citation_version}) does not match CMake project version (${project_version})"
  exit 1
fi

latest_changelog_date="$(sed -nE 's/^## \[[0-9]+\.[0-9]+\.[0-9]+\] - ([0-9]{4}-[0-9]{2}-[0-9]{2})$/\1/p' CHANGELOG.md | head -n1)"
citation_date="$(sed -rn 's/date-released: ([0-9]{4}-[0-9]{2}-[0-9]{2})/\1/p' CITATION.cff | head -n1)"

if [[ -z "$latest_changelog_date" || -z "$citation_date" ]]; then
  echo "Unable to parse changelog/citation release dates"
  exit 1
fi

if [[ "$latest_changelog_date" != "$citation_date" ]]; then
  echo "CITATION.cff date-released (${citation_date}) does not match latest changelog release (${latest_changelog_date})"
  exit 1
fi

echo "[check-metadata] validating there are no legacy repository URLs..."
set +e
legacy_matches="$(git grep -n -E 'github\.com[:/]zachasme/h3-pg(\.git)?')"
legacy_status=$?
set -e

if [[ $legacy_status -eq 0 ]]; then
  echo "Found legacy GitHub URLs:"
  echo "$legacy_matches"
  exit 1
fi

if [[ $legacy_status -ne 1 ]]; then
  echo "Error while scanning for legacy URLs"
  exit 1
fi

echo "[check-metadata] OK"
