#!/usr/bin/env bash
# Fail when a production source file outgrows the module budget.
#
# The hard limit is 1,200 lines (warn at 800). The allowlist is the *debt
# ledger*: every entry names a file that the #1723 split has not reached yet.
# Remove an entry in the same commit that splits the file; never add one for
# new code.
set -euo pipefail

limit="${LIMIT:-1200}"
warn="${WARN:-800}"
allowlist="
src/relationships.rs
src/projects.rs
src/commands/agents.rs
src/hierarchy.rs
src/ui/schedule.rs
src/commands/edit.rs
src/sync/beads.rs
src/views/registry.rs
src/ui/triage.rs
src/workflow.rs
src/cycle_schedule/generate.rs
src/planning.rs
src/commands/epic.rs
src/keybindings.rs
src/ui/form.rs
src/cli.rs
src/commands/create.rs
src/recurrence/rule.rs
src/sync/adapters.rs
src/commands/view.rs
src/commands/link.rs
src/ui/planning.rs
src/commands/mv.rs
src/capacity/portable.rs
src/ui/commandbar.rs
src/time_tracking/portable.rs
src/search/filter.rs
src/wip/config.rs
src/analytics/series.rs
"

fail=0
while IFS= read -r file; do
    case "$file" in */tests/*|*/tests.rs) continue;; esac
    lines=$(wc -l <"$file")
    if [ "$lines" -le "$limit" ]; then
        if [ "$lines" -gt "$warn" ]; then
            echo "module nearing budget: $file has $lines lines (warn $warn)" >&2
        fi
        continue
    fi
    if grep -qxF "$file" <<<"$allowlist"; then
        continue
    fi
    echo "module too large: $file has $lines lines (limit $limit)" >&2
    echo "  split it, or add it to the allowlist only while an open WP owns it" >&2
    fail=1
done < <(find src -name '*.rs' | sort)

exit "$fail"
