#!/usr/bin/env bash
set -u

ROOT="${1:-/Users/jack/code/010-cpt}"
OUT="${2:-/Users/jack/code/010-cpt/output/long-horizon-refactor-20260503/evidence/bounded-status.tsv}"
TIMEOUT_SECONDS="${TIMEOUT_SECONDS:-8}"

mkdir -p "$(dirname "$OUT")"
printf 'path\tvcs\tstatus\tcount_or_reason\n' > "$OUT"

find "$ROOT" -maxdepth 3 -type d \( -name .git -o -name .svn \) -prune -print |
  sed 's#/.git##; s#/.svn##' |
  sort |
  while IFS= read -r project; do
    vcs="unknown"
    [ -d "$project/.git" ] && vcs="git"
    [ -d "$project/.svn" ] && vcs="svn"

    if [ "$vcs" = "svn" ]; then
      printf '%s\t%s\tblocked\tsvn_status_not_checked\n' "$project" "$vcs" >> "$OUT"
      continue
    fi

    tmp="$(mktemp)"
    marker="$(mktemp)"
    git -C "$project" status --short -uno > "$tmp" 2>&1 &
    pid=$!
    (
      sleep "$TIMEOUT_SECONDS"
      printf 'timeout\n' > "$marker"
      kill -TERM "$pid" 2>/dev/null
    ) &
    watchdog=$!
    wait "$pid"
    rc=$?
    kill "$watchdog" 2>/dev/null
    wait "$watchdog" 2>/dev/null

    if [ -s "$marker" ]; then
      printf '%s\t%s\tblocked\ttimeout_%ss\n' "$project" "$vcs" "$TIMEOUT_SECONDS" >> "$OUT"
    elif [ "$rc" -ne 0 ]; then
      first_line="$(sed -n '1p' "$tmp" | tr '\t' ' ')"
      printf '%s\t%s\tblocked\tgit_status_failed:%s\n' "$project" "$vcs" "$first_line" >> "$OUT"
    else
      count="$(wc -l < "$tmp" | tr -d ' ')"
      printf '%s\t%s\tok\t%s\n' "$project" "$vcs" "$count" >> "$OUT"
    fi

    rm -f "$tmp" "$marker"
  done

printf '%s\n' "$OUT"
