#!/usr/bin/env bash
# One-command field-governance audit (epic #4863, story S1).
# Read-only against prod TiDB (SELECT/SHOW/DESCRIBE only).
#
# Usage:
#   ./run_audit.sh                       # all nine audited objects
#   ./run_audit.sh Opportunity Account   # subset
#
# Env:
#   NEXUSCRM_ENV_FILE  env file with TIDB_PROD_* keys (see README for resolution order)
#   AUDIT_OUT          root directory for run outputs (default: ./audit_out)
#   AUDIT_BASELINE     optional dir with a previous run's CSVs for a bucket-move diff
#
# Freshness by construction: every run writes into a NEW run-scoped directory
# ($AUDIT_OUT/run-<stamp>/) and nothing is ever deleted. A fresh directory
# cannot contain stale artifacts, and previous runs stay intact — which also
# makes them directly usable as AUDIT_BASELINE.

set -euo pipefail

command -v uv >/dev/null 2>&1 || { echo "run_audit.sh requires uv (https://docs.astral.sh/uv/)"; exit 1; }

# Resolve operator-relative paths BEFORE cd'ing to the script directory.
# The AUDIT_OUT default deliberately stays script-relative (./audit_out, which
# the local .gitignore covers); only an explicit override is operator-relative.
abspath() { case "$1" in /*) printf '%s\n' "$1" ;; *) printf '%s/%s\n' "$PWD" "$1" ;; esac; }
if [ -n "${AUDIT_OUT:-}" ]; then ROOT="$(abspath "$AUDIT_OUT")"; else ROOT="audit_out"; fi
BASELINE="${AUDIT_BASELINE:+$(abspath "$AUDIT_BASELINE")}"
if [ -n "${NEXUSCRM_ENV_FILE:-}" ]; then
  NEXUSCRM_ENV_FILE="$(abspath "$NEXUSCRM_ENV_FILE")"
  export NEXUSCRM_ENV_FILE
fi

cd "$(dirname "$0")"

if [ -e "$ROOT" ] && [ ! -d "$ROOT" ]; then
  echo "ERROR: $ROOT exists and is not a directory" >&2
  exit 1
fi

# Allocate a fresh run directory ATOMICALLY: plain mkdir fails on an existing
# path, so existence check and creation are one step — concurrent same-second
# invocations get distinct directories instead of silently sharing one.
mkdir -p "$ROOT"
stamp="$(date +%Y%m%d-%H%M%S)"
OUT="$ROOT/run-$stamp"
n=1
until mkdir "$OUT" 2>/dev/null; do OUT="$ROOT/run-$stamp-$n"; n=$((n + 1)); done
echo "run directory: $OUT"

run() { uv run --with pymysql python "$@"; }

run probe_full_audit.py "$@" --out "$OUT"
run classify_full.py "$@" --out "$OUT"
if [ -n "$BASELINE" ]; then
  run make_tables.py "$@" --out "$OUT" --baseline "$BASELINE"
else
  run make_tables.py "$@" --out "$OUT"
fi
run metrics_summary.py "$@" --out "$OUT" | tee "$OUT/metrics_summary.md"

# Convenience pointer to the newest run; never deletes anything.
ln -sfn "$(basename "$OUT")" "$ROOT/latest"

echo
echo "Done. Outputs in $OUT/ (per-field CSVs, tables/, metrics_summary.md); $ROOT/latest points here"
