#!/usr/bin/env bash
# prompt-optimiser-audit.sh — reconcile per-turn directive-injection breadcrumbs
# against the stored content files (Task 746). A missing content write emits no
# error on its own, so this standing check is the leak detector: for each
# session it prints
#   [prompt-optimiser-audit] session=<id> injected=<N> stored=<M>
# where N is the count of breadcrumb injection lines and M is the count of
# content files. N != M is the leak signature. Every breadcrumb whose file=
# path is absent on disk is named on its own `missing-file=` line.
#
# Usage:
#   prompt-optimiser-audit.sh [--log-dir <dir>] [<session_id>]
# With no <session_id> it walks every session that appears in the breadcrumb
# log. --log-dir overrides the resolved account logs dir (used by tests); the
# default resolves the single account's logs dir, the same dir the hook writes.
#
# Exit codes:
#   0  every reported session reconciles (injected == stored)
#   1  at least one session leaks (injected != stored)
#   2  no log dir could be resolved
set -uo pipefail

LOG_DIR=""
SESSION=""
while [ $# -gt 0 ]; do
  case "$1" in
    --log-dir) LOG_DIR="$2"; shift 2 ;;
    *) SESSION="$1"; shift ;;
  esac
done

# Resolve the account logs dir when not overridden: {installDir}/data/accounts/*/logs.
if [ -z "$LOG_DIR" ]; then
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  PLATFORM_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
  INSTALL_DIR="$(dirname "$PLATFORM_ROOT")"
  for d in "$INSTALL_DIR"/data/accounts/*/logs; do
    [ -d "$d" ] && LOG_DIR="$d" && break
  done
fi
if [ -z "$LOG_DIR" ] || [ ! -d "$LOG_DIR" ]; then
  echo "[prompt-optimiser-audit] no-log-dir resolved=${LOG_DIR:-<none>}" >&2
  exit 2
fi

CRUMB="$LOG_DIR/prompt-optimiser-directive.log"
STORE_ROOT="$LOG_DIR/prompt-optimiser-directives"

# Sessions to report: the explicit arg, else every distinct non-"?" session in
# the breadcrumb log (the breadcrumb's session= is always the last field).
sessions() {
  if [ -n "$SESSION" ]; then
    echo "$SESSION"; return
  fi
  [ -f "$CRUMB" ] || return
  grep -o 'session=[^ ]*$' "$CRUMB" 2>/dev/null | cut -d= -f2 | grep -v '^?$' | sort -u
}

rc=0
while IFS= read -r sid; do
  [ -n "$sid" ] || continue
  injected=0
  # grep -c prints a count AND exits 1 on zero matches, so a `|| echo 0` would
  # double-emit "0\n0"; capture the count and default an empty/unreadable file.
  if [ -f "$CRUMB" ]; then
    injected=$(grep -c "session=$sid\$" "$CRUMB" 2>/dev/null)
    injected=${injected:-0}
  fi
  stored=0
  [ -d "$STORE_ROOT/$sid" ] && stored=$(find "$STORE_ROOT/$sid" -maxdepth 1 -name '*.txt' 2>/dev/null | wc -l | tr -d ' ')
  echo "[prompt-optimiser-audit] session=$sid injected=$injected stored=$stored"
  [ "$injected" != "$stored" ] && rc=1
  # Name every breadcrumb whose stored file is absent.
  if [ -f "$CRUMB" ]; then
    grep "session=$sid\$" "$CRUMB" 2>/dev/null | grep -o 'file=[^ ]*' | cut -d= -f2- | while IFS= read -r f; do
      [ "$f" = "-" ] && continue
      [ -e "$f" ] || echo "[prompt-optimiser-audit] session=$sid missing-file=$f"
    done
  fi
done < <(sessions)

exit "$rc"
