#!/usr/bin/env bash
# Run OMNL IPSAS + journal-matrix anchor and persist JSON + sha256 under artifacts/omnl-reconcile/.
# Usage: from repo root — bash scripts/hybx-omnl/omnl-reconcile-artifact.sh
# Env:
#   OMNL_RECONCILE_ARTIFACT_DIR — output directory (default: $REPO_ROOT/artifacts/omnl-reconcile)
#   OMNL_IPSAS_GL_REGISTRY, OMNL_JOURNAL_MATRIX_PATH — passed through to omnl-reconcile-report.mjs
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
OUT="${OMNL_RECONCILE_ARTIFACT_DIR:-$ROOT/artifacts/omnl-reconcile}"
TS="$(date -u +%Y%m%dT%H%M%SZ)"

mkdir -p "$OUT"
# Invoke the report script with node so stdout is JSON only (npm run adds lifecycle lines).
node "$ROOT/services/token-aggregation/scripts/omnl-reconcile-report.mjs" > "$OUT/omnl-reconcile-${TS}.json"
cp -f "$OUT/omnl-reconcile-${TS}.json" "$OUT/omnl-reconcile-latest.json"

node -e "
const fs = require('fs');
const j = JSON.parse(fs.readFileSync('$OUT/omnl-reconcile-latest.json', 'utf8'));
fs.writeFileSync('$OUT/omnl-reconcile-sha256.txt', String(j.sha256).trim() + '\n');
"

if [[ -n "${GITHUB_SHA:-}" ]] || [[ -n "${GITHUB_RUN_ID:-}" ]]; then
  node -e "
const fs = require('fs');
const o = {
  generatedAt: new Date().toISOString(),
  githubSha: process.env.GITHUB_SHA || null,
  runId: process.env.GITHUB_RUN_ID || null,
  repository: process.env.GITHUB_REPOSITORY || null,
};
fs.writeFileSync('$OUT/omnl-reconcile-ci-meta.json', JSON.stringify(o, null, 2) + '\n');
" 2>/dev/null || true
fi

echo "OMNL reconcile artifacts written:"
echo "  $OUT/omnl-reconcile-${TS}.json"
echo "  $OUT/omnl-reconcile-latest.json"
echo "  $OUT/omnl-reconcile-sha256.txt ($(cat "$OUT/omnl-reconcile-sha256.txt" | tr -d '\n'))"
