#!/usr/bin/env bash
set -Eeuo pipefail

usage() {
  printf 'Usage: %s [repository] [output.md]\n' "${0##*/}" >&2
}

repo=${1:-.}
output=${2:-repo-triage-report.md}

if [[ ! -d "$repo" ]]; then
  usage
  exit 2
fi

repo=$(cd "$repo" && pwd -P)
if [[ "$output" != /* ]]; then
  output="$PWD/$output"
fi

tmpdir=$(mktemp -d)
trap 'rm -rf -- "$tmpdir"' EXIT

files="$tmpdir/files"
if git -C "$repo" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  git -C "$repo" ls-files -co --exclude-standard >"$files"
  vcs="Git"
  revision=$(git -C "$repo" rev-parse --short HEAD 2>/dev/null || printf 'uncommitted')
  dirty=$(git -C "$repo" status --porcelain | wc -l | tr -d ' ')
else
  find "$repo" -type f -not -path '*/.git/*' -printf '%P\n' >"$files"
  vcs="none"
  revision="n/a"
  dirty="n/a"
fi

file_count=$(wc -l <"$files" | tr -d ' ')
tracked_bytes=0
while IFS= read -r relative; do
  [[ -f "$repo/$relative" ]] || continue
  size=$(stat -c %s "$repo/$relative" 2>/dev/null || printf 0)
  tracked_bytes=$((tracked_bytes + size))
done <"$files"

languages="$tmpdir/languages"
awk '
  function ext(path) {
    n=split(path, p, ".")
    return n > 1 ? tolower(p[n]) : "(none)"
  }
  { count[ext($0)]++ }
  END { for (e in count) print count[e], e }
' "$files" | sort -nr | head -10 >"$languages"

manifests="$tmpdir/manifests"
rg -N '(^|/)(package(-lock)?\.json|pnpm-lock\.yaml|yarn\.lock|pyproject\.toml|requirements[^/]*\.txt|Cargo\.(toml|lock)|go\.(mod|sum)|Gemfile(\.lock)?|pom\.xml|build\.gradle(\.kts)?)$' "$files" >"$manifests" || true

risks="$tmpdir/risks"
while IFS= read -r relative; do
  case "$relative" in
    *.pem|*.key|*.p12|*.pfx|*.keystore|.env|*/.env)
      printf '%s\n' "$relative" >>"$risks"
      ;;
  esac
done <"$files"

tests=$({ rg -N '(^|/)(test|tests|spec|__tests__)(/|$)|(_test\.go|_test\.py|\.test\.[jt]sx?|\.spec\.[jt]sx?)$' "$files" || true; } | wc -l | tr -d ' ')
ci=$({ rg -N '(^|/)(\.github/workflows/[^/]+\.ya?ml|\.gitlab-ci\.yml|Jenkinsfile|\.circleci/config\.yml)$' "$files" || true; } | wc -l | tr -d ' ')
docs=$({ rg -Ni '(^|/)(readme|contributing|security|license)(\.[^/]*)?$' "$files" || true; } | wc -l | tr -d ' ')

{
  printf '# Repository triage report\n\n'
  printf 'Generated: `%s`\n\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  printf 'Repository: `%s`\n\n' "$repo"
  printf '## Snapshot\n\n'
  printf '| Metric | Value |\n|---|---:|\n'
  printf '| Version control | %s |\n' "$vcs"
  printf '| Revision | `%s` |\n' "$revision"
  printf '| Working-tree changes | %s |\n' "$dirty"
  printf '| Files | %s |\n' "$file_count"
  printf '| Bytes | %s |\n' "$tracked_bytes"
  printf '| Test-like files | %s |\n' "$tests"
  printf '| CI definitions | %s |\n' "$ci"
  printf '| Core project documents | %s |\n\n' "$docs"
  printf '## File types\n\n| Extension | Files |\n|---|---:|\n'
  while read -r count extension; do
    printf '| `%s` | %s |\n' "$extension" "$count"
  done <"$languages"
  printf '\n## Build and dependency manifests\n\n'
  if [[ -s "$manifests" ]]; then
    sed 's/^/- `/' "$manifests" | sed 's/$/`/'
  else
    printf 'No common manifest detected.\n'
  fi
  printf '\n## Potentially sensitive tracked filenames\n\n'
  if [[ -s "$risks" ]]; then
    sed 's/^/- `/' "$risks" | sed 's/$/`/'
    printf '\nReview these filenames manually. This report does not inspect secret values.\n'
  else
    printf 'No common private-key or environment filenames detected.\n'
  fi
  printf '\n## Recommended next actions\n\n'
  if [[ "$ci" -eq 0 ]]; then
    printf '1. Add a minimal CI workflow that runs the project test and lint commands.\n'
  else
    printf '1. Reproduce the current CI result from a clean checkout.\n'
  fi
  if [[ "$tests" -eq 0 ]]; then
    printf '2. Add one smoke test around the highest-value user path.\n'
  else
    printf '2. Identify the slowest or least reliable test and stabilize it.\n'
  fi
  if [[ -s "$risks" ]]; then
    printf '3. Confirm sensitive-looking files are intentional; rotate any exposed credential.\n'
  else
    printf '3. Run the ecosystem-native dependency and secret scanners.\n'
  fi
  printf '\n## Scope note\n\n'
  printf 'This is deterministic repository inventory, not a security certification. '
  printf 'It reads filenames and metadata but does not transmit repository contents.\n'
} >"$output"

printf '%s\n' "$output"
