#!/usr/bin/env bash
# vibe_report.sh — clone popular Python repos and vibe-check them all
# Output: report.md in the same directory as this script

set -euo pipefail

WORK_DIR=$(mktemp -d)
RESULTS_DIR="$WORK_DIR/results"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPORT="$SCRIPT_DIR/report.md"
mkdir -p "$RESULTS_DIR"
trap 'rm -rf "$WORK_DIR"' EXIT

# Format: "slug|github_path|src_subdir"
REPOS=(
  "django|django/django|django"
  "flask|pallets/flask|src/flask"
  "fastapi|tiangolo/fastapi|fastapi"
  "pandas|pandas-dev/pandas|pandas"
  "scikit-learn|scikit-learn/scikit-learn|sklearn"
  "transformers|huggingface/transformers|src/transformers"
  "pip|pypa/pip|src/pip"
  "ruff|astral-sh/ruff|python"
  "pytest|pytest-dev/pytest|src"
  "bottle|bottlepy/bottle|."
  "requests|psf/requests|src/requests"
  "rich|Textualize/rich|rich"
)

# Format: "category_title|slug1 slug2 slug3"
CATEGORIES=(
  "Web / APIs|django flask fastapi"
  "Data / ML|pandas scikit-learn transformers"
  "Tooling|pip ruff pytest"
  "Fun / Interesting|bottle requests rich"
)

TOTAL=${#REPOS[@]}

# --- progress bar helper ---
# usage: draw_progress current total label [start_epoch]
draw_progress() {
  local current=$1 total=$2 label=$3 start=${4:-0}
  local width=30
  local filled=$(( current * width / total ))
  local empty=$(( width - filled ))
  local bar
  bar="$(printf '█%.0s' $(seq 1 $filled) 2>/dev/null)$(printf '░%.0s' $(seq 1 $empty) 2>/dev/null)"
  local eta=""
  if [ "$start" -gt 0 ] && [ "$current" -gt 0 ]; then
    local elapsed=$(( $(date +%s) - start ))
    local remaining=$(( elapsed * (total - current) / current ))
    if [ "$remaining" -ge 60 ]; then
      eta="  ETA $(( remaining / 60 ))m $(( remaining % 60 ))s"
    else
      eta="  ETA ${remaining}s"
    fi
  fi
  printf "\r  [%s] %d/%d  %s%s" "$bar" "$current" "$total" "$label" "$eta"
}

echo "Generating vibe report..."
echo "Work dir: $WORK_DIR"
echo ""

# --- clone all repos ---
echo "Cloning repos..."
clone_start=$(date +%s)
clone_done=0
for entry in "${REPOS[@]}"; do
  IFS='|' read -r slug gh_path src_subdir <<< "$entry"
  dest="$WORK_DIR/$slug"
  draw_progress "$clone_done" "$TOTAL" "cloning $gh_path..." "$clone_start"
  if git clone --depth=1 "https://github.com/$gh_path.git" "$dest" --quiet 2>&1; then
    if [ "$src_subdir" = "." ]; then
      echo "$dest" > "$RESULTS_DIR/${slug}.src"
    else
      echo "$dest/$src_subdir" > "$RESULTS_DIR/${slug}.src"
    fi
  else
    printf "\n  WARNING: failed to clone %s\n" "$gh_path"
    echo "FAILED" > "$RESULTS_DIR/${slug}.src"
  fi
  clone_done=$(( clone_done + 1 ))
  draw_progress "$clone_done" "$TOTAL" "done" "$clone_start"
done
echo ""
echo ""

echo "Running vibe-check on each repo..."
check_start=$(date +%s)
check_done=0
# --- run vibe-check for each repo and save results ---
for entry in "${REPOS[@]}"; do
  IFS='|' read -r slug gh_path src_subdir <<< "$entry"
  src=$(cat "$RESULTS_DIR/${slug}.src")
  draw_progress "$check_done" "$TOTAL" "checking $slug..." "$check_start"

  if [ "$src" = "FAILED" ]; then
    printf "N/A|clone failed|0|0|\n" > "$RESULTS_DIR/${slug}.result"
    check_done=$(( check_done + 1 ))
    draw_progress "$check_done" "$TOTAL" "skipped (clone failed)" "$check_start"
    continue
  fi

  if [ ! -d "$src" ]; then
    src="$WORK_DIR/$slug"
  fi

  output=$(vibe-check "$src" 2>&1) || true

  files=$(echo "$output" | grep -oE 'Scanned [0-9]+' | grep -oE '[0-9]+' || echo "0")
  violations=$(echo "$output" | grep -oE 'Total violations: [0-9]+' | grep -oE '[0-9]+' || echo "0")
  score=$(echo "$output" | grep -oE 'Vibe score: [0-9]+' | grep -oE '[0-9]+' || echo "0")
  verdict=$(echo "$output" | grep -oE 'Verdict: .+' | sed 's/Verdict: //' || echo "unknown")

  top_rules=$(echo "$output" | grep -oE 'VIB[0-9]+[[:space:]]+[#]+[[:space:]]+[0-9]+' | \
    awk '{print $NF, $1}' | sort -rn | head -5 | \
    awk '{print $2 " (" $1 ")"}' | paste -sd ', ' 2>/dev/null || echo "")

  printf "%s|%s|%s|%s|%s\n" "$score" "$verdict" "$files" "$violations" "$top_rules" \
    > "$RESULTS_DIR/${slug}.result"
  check_done=$(( check_done + 1 ))
  draw_progress "$check_done" "$TOTAL" "$slug — ${score}/100 · ${verdict}" "$check_start"
done
echo ""
echo ""
echo "Writing $REPORT..."

# --- helper to read a field from a result file ---
get_field() {
  local slug=$1
  local field=$2  # 1-indexed
  cut -d'|' -f"$field" < "$RESULTS_DIR/${slug}.result"
}

# --- write report ---
{
  echo "# Vibe Check Report"
  echo ""
  echo "A vibe-check run across 12 of the most popular Python repositories."
  echo "Generated by [vibe-checker](https://github.com/fabiosousa/vibe-checker)."
  echo ""
  echo "---"
  echo ""
  echo "## Summary Table"
  echo ""
  echo "| Repo | Files | Violations | Score | Verdict |"
  echo "|------|------:|-----------:|------:|---------|"

  for entry in "${REPOS[@]}"; do
    IFS='|' read -r slug gh_path _ <<< "$entry"
    score=$(get_field "$slug" 1)
    verdict=$(get_field "$slug" 2)
    files=$(get_field "$slug" 3)
    violations=$(get_field "$slug" 4)
    echo "| [$slug](https://github.com/$gh_path) | $files | $violations | $score/100 | $verdict |"
  done

  echo ""
  echo "---"
  echo ""

  for cat_entry in "${CATEGORIES[@]}"; do
    IFS='|' read -r cat_title cat_slugs <<< "$cat_entry"
    echo "## $cat_title"
    echo ""

    for slug in $cat_slugs; do
      gh_path=""
      for repo_entry in "${REPOS[@]}"; do
        IFS='|' read -r r_slug r_gh _ <<< "$repo_entry"
        if [ "$r_slug" = "$slug" ]; then
          gh_path="$r_gh"
          break
        fi
      done

      score=$(get_field "$slug" 1)
      verdict=$(get_field "$slug" 2)
      files=$(get_field "$slug" 3)
      violations=$(get_field "$slug" 4)
      top=$(get_field "$slug" 5)

      echo "### [$slug](https://github.com/$gh_path) — $score/100 · *$verdict*"
      echo ""
      echo "- **Files scanned:** $files"
      echo "- **Total violations:** $violations"
      echo "- **Top rules triggered:** ${top:-none}"
      echo ""
    done

    echo "---"
    echo ""
  done
} > "$REPORT"

echo "Done. Report written to $REPORT"
