#!/usr/bin/env bash
# Adopt common library in top-N legacy scripts (no lib sourcing yet)
# Safe: inserts only a single line after first SCRIPT_DIR=...BASH_SOURCE occurrence.
# Verifies syntax, reverts on failure. Writes report to docs/SCRIPTS_ADOPTION_PLAN.md

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "/home/intlc/projects/smom-dbis-138/scripts/lib/init.sh"
ROOT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
REPORT="$ROOT_DIR/docs/SCRIPTS_ADOPTION_PLAN.md"
LIMIT=30
APPLY=1

while [[ $# -gt 0 ]]; do
  case "$1" in
    --limit) LIMIT="$2"; shift 2;;
    --dry-run) APPLY=0; shift;;
    *) echo "Unknown arg: $1"; exit 1;;
  esac
done

mkdir -p "$ROOT_DIR/docs"

tmp_list=$(mktemp)
{
  cd "$ROOT_DIR"
  while IFS= read -r -d '' f; do
    # skip if already sourcing lib
    if grep -q 'source "\$SCRIPT_DIR/\../lib/init\.sh"' "$f" 2>/dev/null; then
      continue
    fi
    # require a SCRIPT_DIR with BASH_SOURCE
    if grep -q 'BASH_SOURCE\[0\]' "$f" && grep -q '^SCRIPT_DIR=' "$f"; then
      printf "%s\t%s\n" "$(wc -l < "$f")" "$f"
    fi
  done < <(find scripts -type f -name '*.sh' ! -path '*/lib/*' -print0)
} | sort -rn | head -n "$LIMIT" | cut -f2- > "$tmp_list"
mapfile -t CANDIDATES < "$tmp_list"
rm -f "$tmp_list"

changed=()
skipped=()

{
  echo "# Scripts Adoption Plan"
  echo
  echo "Generated: $(date -Iseconds)"
  echo
  echo "Targeting top $LIMIT legacy scripts (no lib sourcing) to insert: \`source \"$SCRIPT_DIR/../lib/init.sh\"\` after the first \`SCRIPT_DIR=...BASH_SOURCE\` line."
  echo
  for f in "${CANDIDATES[@]}"; do
    rel="${f#$ROOT_DIR/}"
    echo "- [ ] $rel"
  done
} > "$REPORT"

for f in "${CANDIDATES[@]}"; do
  [ -e "$f" ] || continue
  if [ "$APPLY" = "0" ]; then continue; fi
  # backup
  tmp="$(mktemp)"; cp "$f" "$tmp"
  # inject after first SCRIPT_DIR line
  awk -v root="$ROOT_DIR" 'BEGIN{ins=0} {
    print
    if (ins==0 && $0 ~ /^SCRIPT_DIR=/ && $0 ~ /BASH_SOURCE\[0\]/) {
      print "source \"" root "/scripts/lib/init.sh\""
      ins=1
    }
  }' "$f" > "$f.__new__"
  mv "$f.__new__" "$f"
  if ! bash -n "$f"; then
    # revert
    cp "$tmp" "$f"
    rm -f "$tmp"
    skipped+=("$f (syntax failed)")
    continue
  fi
  rm -f "$tmp"
  changed+=("$f")

done

# Append results
{
  echo
  echo "## Results"
  echo
  if [ ${#changed[@]} -gt 0 ]; then
    echo "### Adopted (inserted lib/init):"
    for c in "${changed[@]}"; do echo "- [x] ${c#$ROOT_DIR/}"; done
  else
    echo "No files changed."
  fi
  if [ ${#skipped[@]} -gt 0 ]; then
    echo "\n### Skipped (manual review needed):"
    for s in "${skipped[@]}"; do echo "- $s"; done
  fi
} >> "$REPORT"

echo "Adoption pass complete. Report: $REPORT"
