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

SOURCE_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
RUN_ID=${RUN_ID:-$(date -u +%Y%m%dT%H%M%SZ)-$$}
WORK_ROOT=${WORK_ROOT:-"$HOME/.cache/pdf2html-data-jobs-verify"}
WORK_DIR="$WORK_ROOT/$RUN_ID"
EVIDENCE_DIR=${EVIDENCE_DIR:-"$SOURCE_DIR/evidence/$RUN_ID"}
mkdir -p "$WORK_DIR" "$EVIDENCE_DIR"

case "$WORK_DIR/" in "$SOURCE_DIR/"*) printf 'refusing work directory beneath source tree\n' >&2; exit 70;; esac
# Copy only the standalone consumer inputs. This prevents npm from discovering or
# inheriting the repository's ancestor workspace configuration.
mkdir -p "$WORK_DIR/src" "$WORK_DIR/test" "$WORK_DIR/probe"
cp "$SOURCE_DIR/package.json" "$SOURCE_DIR/tsconfig.json" "$SOURCE_DIR/.npmrc" "$WORK_DIR/"
cp "$SOURCE_DIR"/src/*.ts "$WORK_DIR/src/"
cp "$SOURCE_DIR"/test/*.mjs "$WORK_DIR/test/"
cp "$SOURCE_DIR"/probe/*.ts "$WORK_DIR/probe/"

MANIFEST="$EVIDENCE_DIR/command-manifest.txt"
STATUSES="$EVIDENCE_DIR/exit-statuses.tsv"
: >"$MANIFEST"; printf 'step\texit_status\n' >"$STATUSES"
printf '%s\n' \
  'Environment: PATH=/usr/bin:/bin; npm_config_workspaces=false; npm_config_include_workspace_root=false' \
  'Authentication: inherited from remote user npm config; credential values are never captured' \
  'npm install --ignore-scripts --no-audit --no-fund --workspaces=false' \
  'npm ls --all --json --workspaces=false' \
  'npm run typecheck --workspaces=false' \
  'npm test --workspaces=false' \
  'npm run build --workspaces=false' \
  'npx --no-install tsc --noEmit --strict --skipLibCheck --module NodeNext --moduleResolution NodeNext probe/missing-sqlite-exports.ts (required published-contract probe; nonzero means package export unavailable)' \
  'sha256sum evidence files' >"$MANIFEST"

sanitize() {
  python3 -c 'import re,sys
s=sys.stdin.read()
s=re.sub(r"(https?://)[^/@[:space:]]+@", r"\\1[REDACTED]@", s)
s=re.sub(r"(?im)^([^#\n]*(?:token|password|auth)[^=\n]*=).*$", r"\\1[REDACTED]", s)
print(s,end="")'
}
run_step() {
  name=$1; shift
  set +e
  (cd "$WORK_DIR" && env PATH=/usr/bin:/bin npm_config_workspaces=false npm_config_include_workspace_root=false "$@") \
    > >(sanitize >"$EVIDENCE_DIR/$name.stdout.txt") \
    2> >(sanitize >"$EVIDENCE_DIR/$name.stderr.txt")
  status=$?
  set -e
  printf '%s\t%s\n' "$name" "$status" >>"$STATUSES"
  return "$status"
}

set -e
{
  printf 'run_id=%s\n' "$RUN_ID"
  printf 'host=%s\n' "$(hostname)"
  printf 'started_utc=%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  printf 'source_realpath=%s\n' "$SOURCE_DIR"
  printf 'work_realpath=%s\n' "$WORK_DIR"
  printf 'workspace_ancestor_check=isolated-home-cache\n'
  printf 'node=%s\n' "$(PATH=/usr/bin:/bin /usr/bin/node --version)"
  printf 'npm=%s\n' "$(PATH=/usr/bin:/bin /usr/bin/npm --version)"
  printf 'os=%s\n' "$(uname -srmo)"
} >"$EVIDENCE_DIR/run-metadata.txt"

overall=0
run_step install /usr/bin/npm install --ignore-scripts --no-audit --no-fund --workspaces=false || overall=1
if [ -f "$WORK_DIR/package-lock.json" ]; then cp "$WORK_DIR/package-lock.json" "$EVIDENCE_DIR/package-lock.json"; fi
run_step npm-ls /usr/bin/npm ls --all --json --workspaces=false || overall=1
run_step npm-resolution /usr/bin/npm query ':root, :root > *' --json --workspaces=false || overall=1
run_step typecheck /usr/bin/npm run typecheck --workspaces=false || overall=1
run_step test /usr/bin/npm test --workspaces=false || overall=1
run_step build /usr/bin/npm run build --workspaces=false || overall=1
run_step missing-sqlite-export /usr/bin/npx --no-install tsc --noEmit --strict --skipLibCheck --module NodeNext --moduleResolution NodeNext probe/missing-sqlite-exports.ts || overall=1
if [ -d "$WORK_DIR/dist" ]; then
  (cd "$WORK_DIR" && tar -czf "$EVIDENCE_DIR/build-artifacts.tar.gz" dist)
fi
printf 'finished_utc=%s\noverall_exit_status=%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$overall" >>"$EVIDENCE_DIR/run-metadata.txt"
(cd "$EVIDENCE_DIR" && find . -maxdepth 1 -type f ! -name SHA256SUMS -printf '%P\0' | sort -z | xargs -0 sha256sum >SHA256SUMS)
printf '%s\n' "$EVIDENCE_DIR"
exit "$overall"
