#!/usr/bin/env sh
# scripts/truth-lock-check.sh — Portable CI, Pre-Commit & CLI Reference Auditor (`truth.lock`)
# Screens .bib, .ris, .tex, .qmd, .typ, and .md files (or raw DOIs) against 73,969 Retraction Watch
# records, BLAKE3 claim-drift hashes, and GRIM/Statcheck consistency via Commons Scholar.
#
# Usage:
#   ./scripts/truth-lock-check.sh [files-or-dirs-or-dois...]
#   curl -fsSL https://scholar-cloud.askdavidc.ai/truth-lock.sh | sh -s -- references.bib
#
# Environment:
#   COMMONS_SCHOLAR_URL     Base origin (default: https://scholar-cloud.askdavidc.ai)
#   TRUTH_LOCK_FAIL_ON_RET  "true" (default) to exit 1 when retractions/drift are detected; "false" for warn-only

set -eu

BASE_URL="${COMMONS_SCHOLAR_URL:-https://scholar-cloud.askdavidc.ai}"
BASE_URL="${BASE_URL%/}"
FAIL_ON_RET="${TRUTH_LOCK_FAIL_ON_RET:-true}"
ARTIFACT_NAME="${TRUTH_LOCK_ARTIFACT_NAME:-ci-truth.lock}"

TMP_REFS="$(mktemp "${TMPDIR:-/tmp}/truth-lock-refs.XXXXXX")"
TMP_RESP="$(mktemp "${TMPDIR:-/tmp}/truth-lock-resp.XXXXXX")"
cleanup() {
  rm -f "$TMP_REFS" "$TMP_RESP"
}
trap cleanup EXIT INT TERM

collect_file() {
  f="$1"
  [ -f "$f" ] || return 0
  case "$f" in
    *.bib|*.ris)
      cat "$f" >> "$TMP_REFS"
      printf "\n" >> "$TMP_REFS"
      ;;
    *)
      # Extract DOI patterns (`10.NNNN/...`) and OpenAlex IDs from .tex, .qmd, .typ, .md, .txt
      grep -Eo '(https?://(dx\.)?doi\.org/)?10\.[0-9]{4,9}/[-._;()/:A-Za-z0-9]+' "$f" >> "$TMP_REFS" 2>/dev/null || true
      printf "\n" >> "$TMP_REFS"
      ;;
  esac
}

SCANNED_FILES=0
if [ "$#" -eq 0 ]; then
  # Auto-discover bibliography & manuscript files in current directory (excluding build/vendor dirs)
  for f in $(find . -maxdepth 4 -type f \( -name "*.bib" -o -name "*.ris" -o -name "*.qmd" -o -name "*.tex" -o -name "*.typ" \) \
    ! -path "*/.git/*" ! -path "*/node_modules/*" ! -path "*/target/*" ! -path "*/dist/*" 2>/dev/null); do
    collect_file "$f"
    SCANNED_FILES=$((SCANNED_FILES + 1))
  done
else
  for arg in "$@"; do
    if [ -d "$arg" ]; then
      for f in $(find "$arg" -maxdepth 4 -type f \( -name "*.bib" -o -name "*.ris" -o -name "*.qmd" -o -name "*.tex" -o -name "*.typ" -o -name "*.md" \) \
        ! -path "*/.git/*" ! -path "*/node_modules/*" ! -path "*/target/*" 2>/dev/null); do
        collect_file "$f"
        SCANNED_FILES=$((SCANNED_FILES + 1))
      done
    elif [ -f "$arg" ]; then
      collect_file "$arg"
      SCANNED_FILES=$((SCANNED_FILES + 1))
    else
      printf "%s\n" "$arg" >> "$TMP_REFS"
    fi
  done
fi

# Cap payload to 22 KB for fast deterministic wire audit
head -c 22528 "$TMP_REFS" > "${TMP_REFS}.capped"
mv "${TMP_REFS}.capped" "$TMP_REFS"

if [ ! -s "$TMP_REFS" ]; then
  printf "truth.lock: no bibliography files or DOIs found to screen (scanned %d files).\n" "$SCANNED_FILES"
  exit 0
fi

curl -fsSL -X POST "${BASE_URL}/api/truth-lock/audit?artifact_name=${ARTIFACT_NAME}" \
  -H "Content-Type: text/plain; charset=utf-8" \
  --data-binary "@${TMP_REFS}" > "$TMP_RESP"

if command -v python3 >/dev/null 2>&1; then
  python3 - "$TMP_RESP" "$FAIL_ON_RET" "$@" <<'PY'
import json, os, re, sys

resp_path = sys.argv[1]
fail_on_ret = sys.argv[2].lower() not in ("0", "false", "no")
cli_args = sys.argv[3:]

with open(resp_path, "r", encoding="utf-8") as fh:
    data = json.load(fh)

verdict = data.get("verdict", "UNKNOWN")
clean = bool(data.get("clean", False))
screened = int(data.get("screened_count", 0))
retracted = int(data.get("retracted_count", 0))
stat_flags = int(data.get("statistical_flags_count", 0))
watchlist = int(data.get("retraction_watchlist_size", 73969))
blake3_hex = data.get("audit_blake3", "")
refs = data.get("references", [])

print(f"=== Commons Scholar truth.lock Reference Audit ===")
print(f"Verdict:   {verdict} (screened={screened}, retracted={retracted}, stat_flags={stat_flags}, watchlist={watchlist:,})")
print(f"BLAKE3:    {blake3_hex}")
for r in refs:
    mark = "✗ RETRACTED" if r.get("retracted") else "✓ ACTIVE   "
    ident = r.get("identifier", "")
    title = r.get("title", "")
    print(f"  {mark}  {ident} — {title}")

# Emit GitHub Actions annotations & Markdown Job Summary when running in GitHub Actions
if os.environ.get("GITHUB_ACTIONS") == "true":
    cand_files = [a for a in cli_args if os.path.isfile(a)]
    for r in refs:
        if r.get("retracted"):
            ident = r.get("identifier", "")
            title = r.get("title", "")
            annotated = False
            for cf in cand_files:
                try:
                    lines = open(cf, "r", encoding="utf-8", errors="ignore").splitlines()
                    for idx, ln in enumerate(lines, 1):
                        if ident.lower() in ln.lower():
                            print(f"::error file={cf},line={idx},title=Retracted Citation (truth.lock)::{ident} ({title}) is flagged RETRACTED in Retraction Watch.")
                            annotated = True
                            break
                except OSError:
                    pass
                if annotated:
                    break
            if not annotated:
                print(f"::error title=Retracted Citation (truth.lock)::{ident} ({title}) is flagged RETRACTED in Retraction Watch.")

    summary_path = os.environ.get("GITHUB_STEP_SUMMARY")
    if summary_path:
        with open(summary_path, "a", encoding="utf-8") as sf:
            badge = "🟢 CLEAN" if clean else "🔴 RETRACTION / DRIFT DETECTED"
            sf.write(f"## 🔒 `truth.lock` Citation & Retraction Audit — {badge}\n\n")
            sf.write(f"- **Screened references:** `{screened}` against `{watchlist:,}` Retraction Watch records\n")
            sf.write(f"- **Retracted citations:** `{retracted}` · **Statistical flags:** `{stat_flags}`\n")
            sf.write(f"- **Audit BLAKE3 receipt:** `{blake3_hex}`\n\n")
            if refs:
                sf.write("| Status | Identifier | Title |\n| --- | --- | --- |\n")
                for r in refs:
                    st = "🔴 **RETRACTED**" if r.get("retracted") else "🟢 Active"
                    sf.write(f"| {st} | `{r.get('identifier','')}` | {r.get('title','').replace('|','/')} |\n")
                sf.write("\n")

if not clean and fail_on_ret:
    sys.exit(1)
PY
else
  cat "$TMP_RESP"
  printf "\n"
  if grep -q '"clean":false' "$TMP_RESP" && [ "$FAIL_ON_RET" = "true" ]; then
    exit 1
  fi
fi
