#!/bin/sh
# The tier manifest (ci/tiers.tsv) against the tree. See docs/design/keel.md.
#
#   sh test/pic/tiers.sh              check (make test-docs runs it)
#   sh test/pic/tiers.sh --selftest   plant each violation in a temp copy; each check must fail
#   sh test/pic/tiers.sh --table      print the generated table for docs/dev/tiers.md
#   sh test/pic/tiers.sh --report [CHECKIN]
#                                     core size, allowance, core churn since CHECKIN
#
# Checks: 1 every src file has a row and every row a file; 2 core includes only core headers;
# 3 src/tui includes only tui headers and a short list; 4 no vendor or model name in core;
# 5 the core files, as one unit, link with the vendored libraries alone, but for the symbols
# ci/tiers.stubs lists; 6 tiers.allow and tiers.stubs never outgrow the counts in tiers.tsv's
# header; 7 docs/dev/tiers.md is current. Check 5 runs when TIERS_CORE_LINK names the vendored
# objects and libraries to link with (make test-docs sets it); CC is the compiler.
set -eu
SELF=$(cd "$(dirname -- "$0")" && pwd)/$(basename -- "$0")
ROOT=${TIERS_ROOT:-$(cd "$(dirname -- "$0")/../.." && pwd)}
cd "$ROOT"
TSV=ci/tiers.tsv
ALLOW=ci/tiers.allow
STUBS=ci/tiers.stubs
DOC=docs/dev/tiers.md
TUI_OK="pic.h platform.h input.h"
VENDORS='claude-|gpt-|gemini|deepseek|openrouter|anthropic|openai|sonnet|haiku|opus|grok|mistral|llama|qwen'
GENERATED="changelog.inc manual.inc"

T=$(mktemp -d "${TMPDIR:-/tmp}/pic-tiers.XXXXXX")
trap 'rm -rf -- "$T"' EXIT HUP INT TERM

rows() { grep -v '^#' "$TSV" | grep -v '^path	' || true; }
allow_lines() { grep -v '^[[:space:]]*#' "$ALLOW" | grep -v '^[[:space:]]*$' || true; }
stub_lines() { grep -v '^[[:space:]]*#' "$STUBS" | grep -v '^[[:space:]]*$' || true; }
tier_of() { rows | awk -F'\t' -v p="$1" '$1 == p { print $2 }'; }

table() {
    printf '| Tier | Files |\n|---|---|\n'
    for t in core bundled client root data; do
        printf '| %s | %s |\n' "$t" "$(rows | awk -F'\t' -v t="$t" '$2 == t' | wc -l | tr -d ' ')"
    done
    printf '\n| File | Tier | Seam | Clock | Why |\n|---|---|---|---|---|\n'
    rows | awk -F'\t' '{ printf "| `%s` | %s | %s | %s | %s |\n", $1, $2, $3, $4, $5 }'
}

src_files() {
    find src \( -name '*.c' -o -name '*.h' -o -name '*.inc' \) | sort | while IFS= read -r f; do
        skip=0
        for g in $GENERATED; do [ "$(basename -- "$f")" = "$g" ] && skip=1; done
        [ $skip = 1 ] || printf '%s\n' "$f"
    done
}

# The src file an include names, or nothing for system and vendored headers and generated data.
resolve() {
    case "$2" in *.inc) return 0 ;; esac
    for c in "$(dirname -- "$1")/$2" "src/$2"; do
        [ -f "$c" ] && { printf '%s\n' "$c" | sed 's|/\./|/|'; return 0; }
    done
    return 0
}

includes() {
    grep -h '^[[:space:]]*#[[:space:]]*include[[:space:]]*"' "$1" | sed 's/^[^"]*"\([^"]*\)".*/\1/'
}

failed=0
err() { printf 'tiers: %s\n' "$*" >&2; failed=1; }

check() {
    [ -f "$TSV" ] || { err "check 1: $TSV is missing"; return; }
    [ -f "$ALLOW" ] || { err "check 1: $ALLOW is missing"; return; }
    : > "$T/used"

    # Check 1: rows and files agree; every row is well formed.
    src_files > "$T/files"
    rows | cut -f1 | sort > "$T/rowfiles"
    comm -23 "$T/files" "$T/rowfiles" | while IFS= read -r f; do
        printf 'tiers: check 1: %s has no row in %s\n' "$f" "$TSV" >&2
    done 2> "$T/c1"
    comm -13 "$T/files" "$T/rowfiles" | while IFS= read -r f; do
        printf 'tiers: check 1: %s names %s, which is not in src/\n' "$TSV" "$f" >&2
    done 2>> "$T/c1"
    [ ! -s "$T/c1" ] || { cat "$T/c1" >&2; failed=1; }
    rows | awk -F'\t' '
        NF != 5 { printf "tiers: check 1: %s: row for %s needs 5 tab-separated fields\n", FILENAME, $1; bad = 1; next }
        $2 !~ /^(core|bundled|client|root|data)$/ { printf "tiers: check 1: %s has tier %s\n", $1, $2; bad = 1 }
        $4 !~ /^(durability|os|vendor|pi|taste)$/ { printf "tiers: check 1: %s has clock %s\n", $1, $4; bad = 1 }
        $5 == "" { printf "tiers: check 1: %s has no reason\n", $1; bad = 1 }
        END { exit bad }' > "$T/c1b" 2>&1 || { cat "$T/c1b" >&2; failed=1; }

    # The allowance: well-formed lines only.
    allow_lines | while IFS= read -r line; do
        set -- $line
        kind=$1
        case "$kind" in
        include|name) [ $# -ge 4 ] || printf 'tiers: %s: "%s" needs: %s FILE TARGET reason\n' "$ALLOW" "$line" "$kind" ;;
        *) printf 'tiers: %s: unknown kind in "%s"\n' "$ALLOW" "$line" ;;
        esac
    done > "$T/allowbad" 2>&1
    [ ! -s "$T/allowbad" ] || { cat "$T/allowbad" >&2; failed=1; }

    # Checks 2 and 3: includes.
    rows | while IFS="$(printf '\t')" read -r f tier rest; do
        [ -f "$f" ] || continue
        case "$tier" in core|client) ;; *) continue ;; esac
        case "$f" in *.inc) continue ;; esac
        includes "$f" | while IFS= read -r h; do
            target=$(resolve "$f" "$h")
            [ -n "$target" ] || continue
            [ "$target" != "$f" ] || continue
            if [ "$tier" = core ]; then
                [ "$(tier_of "$target")" = core ] && continue
                chk=2; why="core file includes $target, which is $(tier_of "$target")"
            else
                case "$target" in src/tui/*) continue ;; esac
                case " $TUI_OK " in *" $(basename -- "$target") "*) continue ;; esac
                chk=3; why="client file includes $target, which is not a tui header or on the short list ($TUI_OK)"
            fi
            if allow_lines | awk -v f="$f" -v t="$target" '$1 == "include" && $2 == f && $3 == t { found = 1 } END { exit !found }'; then
                printf 'include %s %s\n' "$f" "$target" >> "$T/used"
            else
                printf 'tiers: check %s: %s: %s\n' "$chk" "$f" "$why" >&2
                echo bad >> "$T/c23"
            fi
        done
    done 2>&1 | cat >&2
    [ ! -f "$T/c23" ] || failed=1

    # Check 4: vendor and model names in core sources.
    rows | awk -F'\t' '$2 == "core" { print $1 }' | while IFS= read -r f; do
        [ -f "$f" ] || continue
        case "$f" in *.inc) continue ;; esac
        grep -ioE "$VENDORS" "$f" | tr 'A-Z' 'a-z' | sort -u | while IFS= read -r w; do
            if allow_lines | awk -v f="$f" -v w="$w" '$1 == "name" && $2 == f && $3 == w { found = 1 } END { exit !found }'; then
                printf 'name %s %s\n' "$f" "$w" >> "$T/used"
            else
                printf 'tiers: check 4: %s names %s; core holds no vendor or model name\n' "$f" "$w" >&2
                echo bad >> "$T/c4"
            fi
        done
    done 2>&1 | cat >&2
    [ ! -f "$T/c4" ] || failed=1

    # An allowance line that excuses nothing is a stale line: delete it.
    allow_lines | awk '{ print $1, $2, $3 }' | sort > "$T/allow.keys"
    sort -u "$T/used" > "$T/used.keys"
    comm -23 "$T/allow.keys" "$T/used.keys" | while IFS= read -r l; do
        printf 'tiers: check 6: %s: "%s" excuses nothing any more; delete the line\n' "$ALLOW" "$l" >&2
    done 2> "$T/stale"
    [ ! -s "$T/stale" ] || { cat "$T/stale" >&2; failed=1; }

    # Check 6: the ratchet.
    n=$(allow_lines | wc -l | tr -d ' ')
    max=$(sed -n 's/^# allowance: *\([0-9][0-9]*\).*/\1/p' "$TSV" | head -1)
    if [ -z "$max" ]; then
        err "check 6: $TSV's header has no '# allowance: N' line"
    elif [ "$n" -gt "$max" ]; then
        err "check 6: $ALLOW has $n lines; $TSV records $max. The allowance only shrinks"
    elif [ "$n" -lt "$max" ]; then
        printf 'tiers: note: %s has %s lines, fewer than the recorded %s; lower "# allowance:" in %s\n' "$ALLOW" "$n" "$max" "$TSV" >&2
    fi

    # Check 5: core alone. The core .c files as one unit (tools/amalgamate.sh), linked with the
    # vendored libraries and an empty main and nothing else; every symbol left undefined is
    # one core takes from a bundled file, and must be a line of ci/tiers.stubs.
    if [ -n "${TIERS_CORE_LINK:-}" ]; then
        [ -f "$STUBS" ] || { err "check 5: $STUBS is missing"; return; }
        rows | awk -F'\t' '$2 == "core" && $1 ~ /\.c$/ { print $1 }' > "$T/core.list"
        sh tools/amalgamate.sh $(cat "$T/core.list") > "$T/core.c"
        printf 'int main(void) { return 0; }\n' > "$T/main.c"
        if ! ${CC:-cc} -std=c11 -O0 -w -D_DEFAULT_SOURCE -D_DARWIN_C_SOURCE -D_GNU_SOURCE -Isrc -isystem vendor/libfossil \
            -isystem vendor/zlib -DHAVE_LIBFOSSIL_CONFIG_H -isystem vendor/bearssl/inc -c -o "$T/core.o" "$T/core.c" \
            > "$T/cc.out" 2>&1; then
            err "check 5: the core files do not compile alone:"; sed 's/^/  /' "$T/cc.out" | head -20 >&2
        else
            ${CC:-cc} -c -o "$T/main.o" "$T/main.c"
            # shellcheck disable=SC2086 # the list is words
            ${CC:-cc} -o "$T/core" "$T/core.o" "$T/main.o" $TIERS_CORE_LINK > "$T/ld.out" 2>&1 || true
            # Apple ld: "_sym", referenced from; GNU ld: undefined reference to `sym'; lld: undefined symbol: sym
            sed -n -e 's/^[[:space:]]*"_\([A-Za-z0-9_]*\)", referenced from.*/\1/p' \
                -e "s/.*undefined reference to \`\\([A-Za-z0-9_]*\\)'.*/\\1/p" \
                -e 's/.*undefined symbol: \([A-Za-z0-9_]*\).*/\1/p' "$T/ld.out" | sort -u > "$T/needs"
            if [ ! -s "$T/needs" ] && [ ! -x "$T/core" ]; then
                err "check 5: the core files did not link, for no undefined symbol:"; sed 's/^/  /' "$T/ld.out" | head -20 >&2
            fi
            stub_lines | awk '{ print $1 }' | sort -u > "$T/stubs"
            comm -23 "$T/needs" "$T/stubs" | while IFS= read -r sym; do
                printf 'tiers: check 5: core needs %s, defined outside core; reach it through a seam\n' "$sym" >&2
            done 2> "$T/c5"
            comm -13 "$T/needs" "$T/stubs" | while IFS= read -r sym; do
                printf 'tiers: check 5: %s: core no longer needs %s; delete the line\n' "$STUBS" "$sym" >&2
            done 2>> "$T/c5"
            [ ! -s "$T/c5" ] || { cat "$T/c5" >&2; failed=1; }
        fi
        n=$(stub_lines | wc -l | tr -d ' ')
        max=$(sed -n 's/^# stubs: *\([0-9][0-9]*\).*/\1/p' "$TSV" | head -1)
        if [ -z "$max" ]; then
            err "check 6: $TSV's header has no '# stubs: N' line"
        elif [ "$n" -gt "$max" ]; then
            err "check 6: $STUBS has $n lines; $TSV records $max. The stubs only shrink"
        elif [ "$n" -lt "$max" ]; then
            printf 'tiers: note: %s has %s lines, fewer than the recorded %s; lower "# stubs:" in %s\n' "$STUBS" "$n" "$max" "$TSV" >&2
        fi
    fi

    # Check 7: docs/dev/tiers.md carries the generated table.
    awk '/<!-- tiers:begin -->/ { on = 1; next } /<!-- tiers:end -->/ { on = 0 } on' "$DOC" 2>/dev/null > "$T/doc.tab" || true
    table > "$T/gen.tab"
    cmp -s "$T/doc.tab" "$T/gen.tab" || err "check 7: $DOC's table differs from $TSV; regenerate it with: sh test/pic/tiers.sh --table"
}

report() {
    since=${1:-}
    core=$(rows | awk -F'\t' '$2 == "core" { print $1 }')
    lines=0
    for f in $core; do
        case "$f" in *.c|*.h) lines=$((lines + $(wc -l < "$f"))) ;; esac
    done
    printf 'core lines: %s (%s files, .c and .h)\n' "$lines" "$(printf '%s\n' "$core" | wc -l | tr -d ' ')"
    printf 'allowance lines: %s (recorded: %s)\n' "$(allow_lines | wc -l | tr -d ' ')" \
        "$(sed -n 's/^# allowance: *\([0-9][0-9]*\).*/\1/p' "$TSV" | head -1)"
    if ! command -v zit > /dev/null 2>&1 || ! zit timeline -n 1 > /dev/null 2>&1; then
        printf 'core churn: unavailable (no zit repository here)\n'
        return 0
    fi
    : > "$T/churn"
    for f in $core; do
        case "$f" in *.inc) continue ;; esac
        zit timeline -F oneline -p "$f" -n 1000 | sed 's/^M //; s/^ *//' |
            awk -v s="$since" -v f="$f" 's != "" && index($1, s) == 1 { exit } { h = $1; $1 = $2 = $3 = ""; sub(/^ +/, ""); printf "%s\t%s\t%s\n", h, f, $0 }' |
            grep -v "$(printf '\t')land " >> "$T/churn" || true
    done
    since_label=${since:-the beginning}
    printf 'core churn since %s: %s check-ins touching core files\n' "$since_label" "$(cut -f1 "$T/churn" | sort -u | wc -l | tr -d ' ')"
    cut -f2 "$T/churn" | sort | uniq -c | sort -rn | head -10 | awk '{ printf "  %s %s\n", $1, $2 }'
    vendor=$(grep -iE "$(printf '\t')[^$(printf '\t')]*($VENDORS|price|pricing|catalog)" "$T/churn" | cut -f1 | sort -u | wc -l | tr -d ' ')
    printf 'vendor-driven core changes: %s (check-in comments naming a vendor, model, price or catalog)\n' "$vendor"
}

selftest() {
    fail=0
    base=$T/base
    mkdir -p "$base/docs/dev"
    mkdir -p "$base/tools"
    cp -R src ci "$base/"
    cp tools/amalgamate.sh "$base/tools/"
    ln -s "$ROOT/vendor" "$base/vendor" # check 5 compiles against the real vendored headers
    cp "$DOC" "$base/docs/dev/"
    run() { TIERS_ROOT=$1 sh "$SELF" 2>&1; }
    out=$(run "$base") || { printf 'selftest: the clean copy fails:\n%s\n' "$out" >&2; exit 1; }
    plant() { # name, expected message, then a shell snippet run inside the copy
        name=$1; want=$2; shift 2
        w=$T/plant-$name
        rm -rf "$w"; cp -R "$base" "$w"
        ( cd "$w" && eval "$@" )
        if out=$(run "$w"); then
            printf 'selftest: %s: the check passed on a planted violation\n' "$name" >&2; fail=1
        else
            case "$out" in *"$want"*) printf 'ok   %s\n' "$name" ;;
            *) printf 'selftest: %s: failed, but not with "%s":\n%s\n' "$name" "$want" "$out" >&2; fail=1 ;; esac
        fi
    }
    plant unclassified-file "check 1" 'echo "int x;" > src/newfile.c'
    plant stale-row "check 1" 'rm src/tree.c'
    plant core-includes-bundled "check 2" 'echo "#include \"compact.h\"" >> src/store.c'
    plant tui-reaches-core "check 3" 'echo "#include \"hooks.h\"" >> src/tui/editor.c'
    plant vendor-name-in-core "check 4" 'echo "/* claude-3 */" >> src/tree.c'
    if [ -n "${TIERS_CORE_LINK:-}" ]; then
        plant core-needs-bundled "check 5" 'printf "const char *pic_lapse_mode(void);\nconst char *pic_tiers_planted(void) { return pic_lapse_mode(); }\n" >> src/tree.c'
        plant stale-stub "no longer needs" 'echo "pic_tiers_planted planted" >> ci/tiers.stubs && sed "s/^# stubs: \([0-9]*\)/# stubs: 99/" ci/tiers.tsv > t && mv t ci/tiers.tsv'
        plant stubs-grow "check 6" 'sed "s/^# stubs: \([0-9]*\)/# stubs: 1/" ci/tiers.tsv > t && mv t ci/tiers.tsv'
    else
        printf 'skip check 5: TIERS_CORE_LINK is not set\n'
    fi
    plant allowance-grows "check 6" 'echo "name src/tree.c claude- planted" >> ci/tiers.allow'
    plant stale-allowance "excuses nothing" 'echo "include src/tree.c src/models.h planted" >> ci/tiers.allow'
    plant stale-doc "check 7" 'sed "s/the conversation tree over entries/changed/" ci/tiers.tsv > t && mv t ci/tiers.tsv'
    [ $fail = 0 ] || exit 1
    printf 'selftest: every check fails on its planted violation\n'
}

case "${1:-}" in
--table) rows > /dev/null; table; exit 0 ;;
--report) shift; report "$@"; exit 0 ;;
--selftest) selftest; exit 0 ;;
'') check; [ $failed = 0 ] && printf 'PASS: tiers (%s files, %s allowance lines%s)\n' "$(rows | wc -l | tr -d ' ')" "$(allow_lines | wc -l | tr -d ' ')" \
    "$([ -n "${TIERS_CORE_LINK:-}" ] && printf ', core links alone but for %s stubs' "$(stub_lines | wc -l | tr -d ' ')")"; exit $failed ;;
*) printf 'usage: sh test/pic/tiers.sh [--selftest | --table | --report [CHECKIN]]\n' >&2; exit 2 ;;
esac
