#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# Scope check for one step.
#
#   scripts/check-scope <rev> <final> <brief>
#
# Fails when a file in <rev>..<final> is not claimed by IN SCOPE in <brief>, or when a residual
# trigger matches a path in the diff and the brief does not carry that residual. Always prints
# `claimed: <patterns>` (backticks are stripped from IN SCOPE tokens, and the printed set is what
# the gate matched against) and `tripped: <ids>` (or `tripped: none`) naming every residual whose
# trigger matched the diff; reports copy those lines rather than recomputing them.
#
# docs/research/ is allowed implicitly: a report lands in the diff by design, and forcing it into
# every IN SCOPE is noise. Renames are not collapsed, so a file renamed onto an in-scope name is
# still caught by its old path.
#
# IN SCOPE entries are the text after an `IN SCOPE:` header and every indented line under it,
# separated by commas or whitespace. Field headers may be multiple words (`OUT OF SCOPE:`).

# Operates on the repository it is invoked from, so a caller in a worktree checks that worktree.
# The brief path is resolved before changing directory, so a relative path still works.
set -euo pipefail

if [[ $# -ne 3 ]]; then
    echo "usage: scripts/check-scope <rev> <final> <brief>" >&2
    exit 2
fi

REV="$1"
FINAL="$2"
BRIEF="$3"

# Operate on the repository this was invoked from, so a caller in a subdirectory or a worktree
# checks that repository. Relative paths below are repository-relative for the same reason.
cd "$(git rev-parse --show-toplevel)"

if [[ ! -f "$BRIEF" ]]; then
    echo "scope: no brief at $BRIEF" >&2
    exit 2
fi
BRIEF="$(cd "$(dirname "$BRIEF")" && pwd)/$(basename "$BRIEF")"

if ! git rev-parse --verify --quiet "$REV^{commit}" >/dev/null; then
    echo "scope: no revision $REV" >&2
    exit 2
fi
if ! git rev-parse --verify --quiet "$FINAL^{commit}" >/dev/null; then
    echo "scope: no revision $FINAL" >&2
    exit 2
fi

# Renames are not collapsed, so a file renamed onto an in-scope name is caught by its old path.
# `added` is tracked separately: a report lands in the diff by design, but an existing document
# under docs/research/ being rewritten is a change the brief must claim like any other.
changed="$(git diff --no-renames --name-only "$REV".."$FINAL")"
added="$(git diff --no-renames --name-only --diff-filter=A "$REV".."$FINAL" || true)"
if [[ -z "$changed" ]]; then
    echo "scope: $REV..$FINAL is empty; is FINAL the right sha?" >&2
    exit 1
fi

# Patterns claimed by the brief. A header is an upper-case line ending in a colon, which is what
# stops OUT OF SCOPE: from being read as more IN SCOPE.
claimed="$(awk '
    /^IN SCOPE:/{ sub(/^IN SCOPE:[ \t]*/, ""); in_scope=1; if (length) print; next }
    in_scope && /^[A-Z][A-Z ]*:/{ in_scope=0 }
    in_scope { print }
' "$BRIEF" | tr -d '`' | tr ',' ' \t' | tr -s ' \t' '\n' | grep -v '^$' || true)"

if [[ -z "$claimed" ]]; then
    echo "scope: no IN SCOPE entries found in $BRIEF" >&2
    exit 1
fi

# The claimed set is mechanical and was invisible until a report said so — a backticked or
# prose-junk token matched nothing while looking claimed. This line is the tripped move again.
echo "claimed: $(tr '\n' ' ' <<<"$claimed" | sed 's/[[:space:]]*$//')"

matches() {
    local path="$1" pattern
    while IFS= read -r pattern; do
        # shellcheck disable=SC2254
        [[ "$path" == $pattern ]] && return 0
    done <<<"$claimed"
    return 1
}

status=0
tripped=""

while IFS= read -r path; do
    [[ -z "$path" ]] && continue
    if [[ "$path" == docs/research/* ]] && grep -qxF -- "$path" <<<"$added"; then
        continue
    fi
    if ! matches "$path"; then
        echo "scope: $path is in the diff and not in IN SCOPE" >&2
        status=1
    fi
done <<<"$changed"

# Residual triggers. Rows are selected by having a valid state, not by position, so the store's
# shape table is skipped without depending on how many lines precede the entries.
store=docs/residuals.md
if [[ -f "$store" ]]; then
    rows="$(grep -E '^\|' "$store" || true)"
    while IFS='|' read -r _raw id state trigger _rest; do
        clean() { printf '%s' "$1" | tr -d '`' | sed 's/^[[:space:]]*//; s/[[:space:]]*$//'; }
        id="$(clean "$id")"
        state="$(clean "$state")"
        trigger="$(clean "$trigger")"
        [[ "$state" == "accepted" || "$state" == "rejected" ]] || continue
        [[ -n "$trigger" && -n "$id" ]] || continue
        # Commas and whitespace separate globs. read -ra does not glob-expand, so a pattern that
        # happens to match something in the working tree is still matched as written.
        read -ra patterns <<<"$(printf '%s' "$trigger" | tr ',' ' ')"
        for pattern in "${patterns[@]}"; do
            [[ -n "$pattern" ]] || continue
            while IFS= read -r path; do
                # shellcheck disable=SC2254
                if [[ "$path" == $pattern ]]; then
                    if ! grep -qwF -- "$id" <<<"$tripped"; then
                        tripped="${tripped:+$tripped }$id"
                    fi
                    if ! grep -qwF -- "$id" "$BRIEF"; then
                        echo "scope: $path matches residual $id ($pattern) and the brief does not carry it" >&2
                        status=1
                    fi
                fi
            done <<<"$changed"
        done
    done <<<"$rows"
fi

# The tripped set is mechanical — hand-written TRIPPED lists mis-voted it both ways in one round —
# so reports copy this line instead of recomputing it.
echo "tripped: ${tripped:-none}"

if [[ $status -eq 0 ]]; then
    echo "scope: ok ($(wc -l <<<"$changed" | tr -d ' ') path(s) in $REV..$FINAL)"
fi
exit $status
