#!/usr/bin/env bash
# Acceptance checks 2 to 11 of CARD.md, run for real in throwaway directories
# under the system temp directory. Check 1 is: uv run python -m unittest -q
# Needs uv, git, bun with a warm cache (bun runs with --offline), tmux, script,
# GNU find and stat.
# From this folder: bash acceptance.sh | tee out/acceptance.txt
# It also leaves real tmux captures in out/pane-*.ans for shots.py.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
WORK=$(mktemp -d)
mkdir -p "$WORK/bin" "$HERE/out"
ln -s "$HERE/itemised.py" "$WORK/bin/itemised" # its shebang is uv run --script
export PATH="$WORK/bin:$PATH" LANG=C.UTF-8
unset COLORTERM NO_COLOR
SOCK="$WORK/tmux.sock"
printf 'set -g status off\nset -g history-limit 20000\n' >"$WORK/tmux.conf"
T() { tmux -u -f "$WORK/tmux.conf" -S "$SOCK" "$@"; }
trap 'T kill-server 2>/dev/null; rm -rf "$WORK"' EXIT

say() { printf '\n== %s\n' "$*"; }
show() { sed 's/^/    /' "$1"; }
total() { find . -name .git -prune -o ! -type d -printf '%s\n' | awk '{s += $1} END {print s + 0}'; }
fresh() { rm -rf "${WORK:?}/$1" && mkdir -p "$WORK/$1" && cd "$WORK/$1" || exit 1; }
netline() { grep -E '^net +' "$1" | awk '{print $2}' | tr -d ',+'; }

# pane NAME COLS ROWS [VAR=VALUE...]: a plain bash in the current directory.
# Each time its prompt returns it writes $? to $WORK/rc-NAME and signals the
# tmux channel NAME, so nothing extra is typed into the pane.
pane() {
	local name=$1 cols=$2 rows=$3
	shift 3
	local hook="echo \$? >$WORK/rc-$name; tmux -S $SOCK wait-for -S $name"
	T new-session -d -s "$name" -c "$PWD" -x "$cols" -y "$rows" \
		"env $* PS1='\$ ' PROMPT_COMMAND='$hook' PATH='$PATH' LANG=C.UTF-8 bash --norc --noprofile"
	waitfor "$name"
}
waitfor() { timeout 300 tmux -S "$SOCK" wait-for "$1" || echo "timed out in pane $1"; }
typein() { T send-keys -t "$1" -l "$2" && T send-keys -t "$1" Enter && waitfor "$1"; }
grab() { T capture-pane -p -t "$1" -S - "${@:2}"; }

# Lines of a capture-pane -e -N file that hold cream paper, with their widths.
cat >"$WORK/paper.py" <<'EOF'
import re, sys, unicodedata
def cols(c):
    if unicodedata.category(c) in ("Mn", "Me", "Cf"):
        return 0
    return 2 if unicodedata.east_asian_width(c) in ("W", "F") else 1
paper, widths = False, []
for line in open(sys.argv[1], encoding="utf-8").read().split("\n"):
    w = 0
    for m in re.finditer(r"\x1b\[([0-9;:]*)m|([^\x1b])", line):
        if m.group(2) is not None:
            w += cols(m.group(2)) if paper else 0
            continue
        p = [int(x or 0) for x in re.split("[;:]", m.group(1))]
        i = 0
        while i < len(p):
            if p[i] in (0, 49) or 40 <= p[i] <= 47 or 100 <= p[i] <= 107:
                paper = False
            if p[i] in (38, 48):
                if p[i] == 48:
                    paper = p[i + 1] == 2 and p[i + 2 : i + 5] == [252, 240, 221]
                i += 4 if p[i + 1] == 2 else 2
            i += 1
    if w:
        widths.append(w)
print(f"paper lines in the pane: {len(widths)}, widths seen: {sorted(set(widths))}")
EOF

say "check 2: end to end on real files"
fresh c2
head -c 10 /dev/zero >keep.txt
head -c 100 /dev/zero >edit.txt
head -c 5000 /dev/zero >old.bin
echo "stat before:" && stat -c '  %n %s' ./*
b=$(total)
uv run "$HERE/itemised.py" sh -c 'head -c 1000 /dev/zero > new.bin; echo hello >> edit.txt; rm old.bin' 2>"$WORK/r2.txt"
echo "exit $?"
echo "stat after:" && stat -c '  %n %s' ./*
a=$(total)
echo "by hand: $a - $b = $((a - b)); receipt net: $(netline "$WORK/r2.txt")"
show "$WORK/r2.txt"

say "check 3: the last line"
echo "check 2 ends with:" && tail -n 2 "$WORK/r2.txt" | sed 's/$/|/; s/^/    /'
fresh c3
itemised sh -c 'head -c 3000000 /dev/zero > big' 2>"$WORK/r3a.txt"
echo "big ends with:" && tail -n 2 "$WORK/r3a.txt" | sed 's/^/    /'
fresh c3b
itemised true 2>"$WORK/r3b.txt"
show "$WORK/r3b.txt"

say "check 4: the command is untouched"
fresh c4
uv run "$HERE/itemised.py" sh -c 'echo hi; echo err >&2; exit 3' >"$WORK/o4.txt" 2>"$WORK/e4.txt"
echo "exit $?; stdout bytes: $(od -c "$WORK/o4.txt" | head -n 1); first stderr line: $(head -n 1 "$WORK/e4.txt")"
echo "with 2>/dev/null the terminal gets: $(itemised sh -c 'echo hi; echo err >&2; exit 3' 2>/dev/null | od -c | head -n 1)"
itemised nosuchprogram 2>"$WORK/e4b.txt"
echo "nosuchprogram exit $?, stderr lines $(wc -l <"$WORK/e4b.txt"): $(cat "$WORK/e4b.txt")"
pane c4 100 50 COLORTERM=truecolor
T send-keys -t c4 -l "itemised sleep 30" && T send-keys -t c4 Enter
for _ in $(seq 100); do pid=$(pgrep -nx sleep) && break; sleep 0.1; done
echo "sleep running as pid ${pid:-none}; sending one C-c"
T send-keys -t c4 C-c
waitfor c4
echo "pane exit status: $(cat "$WORK/rc-c4"); kill -0 $pid: $(kill -0 "$pid" 2>&1 | sed 's/.*: //'); pgrep -x sleep: [$(pgrep -x sleep)]"
echo "the pane, first five lines, then the exit row and the last row:"
grab c4 | sed -n '1,5p' | sed 's/ *$/|/; s/^/    /'
grab c4 | grep -E '^(exit|Nothing due)' | sed 's/ *$/|/; s/^/    /'

say "check 5: scope"
fresh c5
mkdir repo second sibling && cd repo && git init -q && echo out/ >.gitignore
itemised sh -c 'mkdir -p out && echo a > out/a.txt && echo z > .git/zz' 2>"$WORK/r5a.txt"
show "$WORK/r5a.txt"
echo "git status --ignored: $(git status --short --ignored | tr '\n' ' ')"
itemised --also ../second sh -c 'echo b > ../second/b.txt; echo s > ../sibling/s.txt' 2>"$WORK/r5b.txt"
show "$WORK/r5b.txt"
echo "listed rows for s.txt: $(grep -cE 's\.txt +\+' "$WORK/r5b.txt"); sibling/s.txt exists: $(test -f ../sibling/s.txt && echo yes)"

say "check 6: grouping"
make='mkdir -p node_modules/pkg; i=1; while [ $i -le 1204 ]; do head -c $i /dev/zero >node_modules/pkg/f$i; i=$((i + 1)); done'
for run in grouped full; do
	fresh "c6-$run" && echo seed >seed.txt
	if [ "$run" = full ]; then set -- --full; else set --; fi
	itemised "$@" sh -c "$make" 2>"$WORK/r6-$run.txt"
	echo "$run: $(wc -l <"$WORK/r6-$run.txt") rows, rows naming node_modules/pkg/f: $(grep -c '^node_modules/pkg/f' "$WORK/r6-$run.txt")"
	grep -E '^(node_modules/ x|created|changed|removed|net)' "$WORK/r6-$run.txt" | sed 's/^/    /'
	grep -oE 'No\. [0-9A-F]{8}' "$WORK/r6-$run.txt" | sed 's/^/    /'
done
set --
grep -E '^(created|changed|removed|net) ' "$WORK/r6-grouped.txt" >"$WORK/t6g"
grep -E '^(created|changed|removed|net) ' "$WORK/r6-full.txt" >"$WORK/t6f"
cmp -s "$WORK/t6g" "$WORK/t6f" && echo "totals identical" || echo "totals differ"
echo "full, first and last three listed rows:"
grep '^node_modules/pkg/f' "$WORK/r6-full.txt" | sed -n '1,3p;1202,1204p' | sed 's/^/    /'

say "check 7: budget"
fresh c7
mkdir big && (cd big && for i in $(seq 500); do : >"f$i"; done)
echo "big holds $(find big | wc -l) entries (find big | wc -l)"
itemised --limit 100 sh -c 'touch big/new1 big/new2; echo hi > note.txt' 2>"$WORK/r7.txt"
show "$WORK/r7.txt"
echo "rows naming big/: $(grep -c '^big/' "$WORK/r7.txt"); big now holds $(find big | wc -l) entries"

say "check 8: the volume"
fresh c8
mkdir root sibling && cd root || exit 1
echo "df avail before: $(df -B1 --output=avail . | tail -n 1)"
itemised dd if=/dev/zero of=../sibling/blob bs=1048576 count=64 conv=fsync 2>"$WORK/r8a.txt"
echo "df avail after: $(df -B1 --output=avail . | tail -n 1)"
show "$WORK/r8a.txt"
itemised true 2>"$WORK/r8b.txt"
echo "a run that changes nothing, Not itemised rows: $(grep -c 'Not itemised' "$WORK/r8b.txt")"
grep -E '^volume' "$WORK/r8b.txt" | sed 's/^/    /'

say "check 9: paper"
fresh c9
echo one >one.txt
pane c9 100 60 COLORTERM=truecolor
typein c9 "itemised ls"
grab c9 -e -N >"$WORK/p9.ans"
echo "lines holding 48;2;252;240;221: $(grep -c '48;2;252;240;221' "$WORK/p9.ans"), holding 38;2;26;26;26: $(grep -c '38;2;26;26;26' "$WORK/p9.ans")"
uv run python "$WORK/paper.py" "$WORK/p9.ans"
fresh c9n
echo one >one.txt
pane c9n 100 60 COLORTERM=truecolor NO_COLOR=1
typein c9n "itemised ls"
echo "NO_COLOR=1 in a truecolor pane, ESC bytes in capture-pane -e: $(grab c9n -e | grep -c $'\033')"
COLORTERM=truecolor script -qec "itemised ls 2>$WORK/r9-file.txt" /dev/null >/dev/null
echo "stderr to a file with stdout on a tty and COLORTERM=truecolor, ESC count: $(grep -c $'\033' "$WORK/r9-file.txt")"
fresh c9l
long="$(printf 'p%.0s' $(seq 50))/$(printf 'q%.0s' $(seq 69))"
echo "path length: ${#long}"
itemised sh -c "mkdir -p ${long%/*} && touch $long" 2>"$WORK/r9-long.txt"
grep -E '^(p|q)' "$WORK/r9-long.txt" | sed 's/^/    /'
uv run python - "$WORK/r9-long.txt" "$long" <<'EOF'
import sys
rows, path = open(sys.argv[1]).read().splitlines(), sys.argv[2]
i = next(i for i, r in enumerate(rows) if r.startswith(path[:20]))
pieces = []
for r in rows[i:]:
    if r.endswith("+0 B"):
        pieces.append(r[:-4].rstrip())
        break
    pieces.append(r)
print(f"pieces {len(pieces)}, joined equals path: {''.join(pieces) == path}")
EOF
fresh c9u
NO_COLOR=1 itemised sh -c 'touch "$(printf "a\033[31mb\nc")"' 2>"$WORK/r9-unsafe.txt"
grep -A1 '^CREATED' "$WORK/r9-unsafe.txt" | sed 's/^/    /'
echo "NO_COLOR=1: ESC bytes $(grep -c $'\033' "$WORK/r9-unsafe.txt"), rows that are a bare c: $(grep -cE '^c( |$)' "$WORK/r9-unsafe.txt")"
fresh c9v
uv run python - <<'EOF'
import os, pty, subprocess
m, s = pty.openpty()
cmd = ["itemised", "sh", "-c", 'touch "$(printf "a\\033[31mb\\nc")"']
env = {**os.environ, "COLORTERM": "truecolor"}
p = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=s, stderr=s, env=env)
os.close(s)
raw = b""
while True:
    try:
        chunk = os.read(m, 65536)
    except OSError:
        break
    if not chunk:
        break
    raw += chunk
p.wait()
paper = b"\x1b[48;2;252;240;221m\x1b[38;2;26;26;26m"
rest = raw.replace(paper, b"").replace(b"\x1b[0m", b"")
row = next(r for r in rest.split(b"\r\n") if r.startswith(b"a\\x1b"))
esc = rest.count(b"\x1b")
print(f"colour run on a pty: {raw.count(paper)} paper rows; ESC left once the paper SGR is removed: {esc}")
print(f"    {row.decode()!r}")
EOF
fresh c9w
printf '漢字の名前%.0s' 1 2 3 4 5 6 7 8 >"$WORK/cjkname"
echo "CJK name: $(wc -m <"$WORK/cjkname") characters"
mkdir "$WORK/c9w-plain" && (cd "$WORK/c9w-plain" && NO_COLOR=1 itemised sh -c 'touch "$(cat ../cjkname)"' 2>"$WORK/r9-cjk.txt")
echo "the same run, plain, has $(wc -l <"$WORK/r9-cjk.txt") rows:"
grep -A3 '^CREATED' "$WORK/r9-cjk.txt" | sed 's/^/    /'
pane c9w 48 120 COLORTERM=truecolor
typein c9w "itemised sh -c 'touch \"\$(cat ../cjkname)\"'"
grab c9w -e -N >"$WORK/p9w.ans"
echo "in a pane exactly 48 columns wide:"
uv run python "$WORK/paper.py" "$WORK/p9w.ans"
grab c9w | awk '/^ +itemised$/ {s = NR} /^(Amount|Change) due|^Nothing due/ {e = NR} END {print "pane lines from the header row to the last row: " e - s + 1}'

say "check 10: a real project run (a copy of this folder running its own tests)"
fresh c10 && mkdir itemised && cp "$HERE/itemised.py" "$HERE/test_itemised.py" itemised/ && cd itemised || exit 1
b=$(total)
itemised uv run python -m unittest -q 2>"$WORK/e10.txt"
echo "exit $?"
a=$(total)
awk '/^ +itemised$/ {p = 1} p' "$WORK/e10.txt" >"$WORK/r10.txt"
echo "independent sum before $b, after $a, difference $((a - b)); receipt net: $(netline "$WORK/r10.txt")"
show "$WORK/r10.txt"
cp "$WORK/r10.txt" "$HERE/out/receipt-unittest.txt"

say "check 11: the second move (bun install, then rm -rf node_modules)"
fresh c11seed
bun init -y >/dev/null 2>&1
bun add --offline vite typescript 2>&1 | tail -n 1 | sed 's/^/    seed: /'
echo "bun cache entries: $(find ~/.bun/install/cache -mindepth 1 -maxdepth 1 | wc -l)"
for size in desk:96 phone:50; do
	tag=${size%%:*} cols=${size##*:}
	fresh "c11-$tag" && cp ../c11seed/package.json ../c11seed/bun.lock .
	b=$(total)
	pane "i-$tag" "$cols" 80 COLORTERM=truecolor
	typein "i-$tag" "itemised bun install --offline"
	a=$(total)
	grab "i-$tag" -e -N >"$HERE/out/pane-install-$tag.ans"
	grab "i-$tag" -J >"$WORK/install-$tag.txt"
	echo "[$tag] find node_modules | wc -l = $(find node_modules | wc -l); files (not directories): $(find node_modules ! -type d | wc -l)"
	echo "[$tag] install: independent difference $((a - b)); receipt net: $(netline "$WORK/install-$tag.txt")"
	grep -E '^(node_modules/|bun\.lock|package\.json|created|changed|removed|net|exit|volume|Not itemised|Not examined: node)|due' "$WORK/install-$tag.txt" | sed 's/ *$//; s/^/    /'
	b=$a
	pane "r-$tag" "$cols" 80 COLORTERM=truecolor
	typein "r-$tag" "itemised rm -rf node_modules"
	a=$(total)
	grab "r-$tag" -e -N >"$HERE/out/pane-remove-$tag.ans"
	grab "r-$tag" -J >"$WORK/remove-$tag.txt"
	echo "[$tag] remove: independent difference $((a - b)); receipt net: $(netline "$WORK/remove-$tag.txt")"
	grep -E '^(node_modules/|created|changed|removed|net|exit|volume|Not itemised)|due' "$WORK/remove-$tag.txt" | sed 's/ *$//; s/^/    /'
	pane "e-$tag" "$cols" 80 COLORTERM=truecolor
	typein "e-$tag" "itemised ls"
	grab "e-$tag" -e -N >"$HERE/out/pane-empty-$tag.ans"
done
grab i-desk >"$HERE/out/pane-install-desk.txt"
grab r-desk >"$HERE/out/pane-remove-desk.txt"
echo
echo "done"
