#!/usr/bin/env bash
# code-docgen test harness — concise, self-contained
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

echo "==> 1. Install to temp prefix"
if [[ -f "$ROOT/install-local.sh" ]]; then
  bash "$ROOT/install-local.sh" --prefix "$TMP/opt"
elif [[ -f "$ROOT/install.sh" ]] && grep -q 'docgen.py' "$ROOT/install.sh" 2>/dev/null && [[ $(wc -l < "$ROOT/install.sh") -lt 50 ]]; then
  bash "$ROOT/install.sh" --prefix "$TMP/opt"
else
  mkdir -p "$TMP/opt/bin"
  cp "$ROOT/docgen.py" "$TMP/opt/bin/docgen"
  chmod 755 "$TMP/opt/bin/docgen"
fi
DOC="$TMP/opt/bin/docgen"
[[ -x "$DOC" ]] || { echo "FAIL: binary missing"; exit 1; }

echo "==> 2. Version / help"
"$DOC" --version | grep -q "1.0.0"
"$DOC" --help   | grep -q "Generate documentation"

echo "==> 3. Generate docs from examples"
"$DOC" -r -o "$TMP/out" --title "Test" "$ROOT/examples"
[[ -f "$TMP/out/documentation.md" ]] || { echo "FAIL: no output"; exit 1; }

echo "==> 4. Spot-check content"
MD="$TMP/out/documentation.md"
grep -q "sample.py"       "$MD"
grep -q "hash_password"   "$MD"
grep -q "sample.js"       "$MD"
grep -q "function init"   "$MD"
grep -q "sample.php"      "$MD"
grep -q "calculateTotal"  "$MD"
grep -q "sample.sh"       "$MD"
grep -q "backup_dir"      "$MD"
grep -q "sample.css"      "$MD"
grep -q -- "--primary"    "$MD"
grep -q "sample.sql"      "$MD"
grep -q "get_user_orders" "$MD"
grep -q "sample.html"     "$MD"
grep -q "Dashboard"       "$MD"

echo "==> 5. HTML format"
"$DOC" -f html -o "$TMP/html" "$ROOT/examples/sample.py"
[[ -f "$TMP/html/documentation.html" ]] || { echo "FAIL: html missing"; exit 1; }

echo
echo "All checks passed."
