#!/usr/bin/env bash
# Remove legacy Azure CLI checks from scripts that already source lib/init.sh and call ensure_azure_cli
# Patterns removed (if present):
#   - if ! command -v az ... fi
#   - az account show ... || { ... }
# Creates report at docs/AZ_CHECKS_CLEANUP.md

to_restore=()
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
REPORT="$ROOT_DIR/docs/AZ_CHECKS_CLEANUP.md"
mkdir -p "$ROOT_DIR/docs"

mapfile -t FILES < <(grep -rl --include='*.sh' 'source "$SCRIPT_DIR/../lib/init.sh"' "$ROOT_DIR/scripts" | xargs -I{} sh -c 'f="$1"; if grep -q "ensure_azure_cli" "$f" && (grep -Eq "^\s*if\s*!\s*command -v\s+az" "$f" || grep -Eq "az\s+account\s+show.*\|\|\s*\{" "$f"); then echo "$f"; fi' sh {})

{
  echo "# Azure CLI Checks Cleanup Report"
  echo
  echo "Generated: $(date -Iseconds)"
  echo
  if [ ${#FILES[@]} -eq 0 ]; then
    echo "No candidates found (all library-enabled scripts rely on ensure_azure_cli)."
  else
    echo "Will clean ${#FILES[@]} files:"
    for f in "${FILES[@]}"; do echo "- ${f#$ROOT_DIR/}"; done
  fi
} > "$REPORT"

for f in "${FILES[@]:-}"; do
  [ -n "$f" ] || continue
  bak="${f}.azbak.$$"; cp "$f" "$bak"; to_restore+=("$bak")
  # Remove 'if ! command -v az ... fi' blocks
  awk '
    BEGIN{skip=0}
    {
      if (skip==0 && $0 ~ /^[[:space:]]*if[[:space:]]*![[:space:]]*command[[:space:]]*-?v[[:space:]]+az[[:space:]]*/){
        skip=1; next
      }
      if (skip==1){
        if ($0 ~ /^[[:space:]]*fi[[:space:]]*$/){ skip=0; next }
        next
      }
      print
    }
  ' "$f" > "$f.__tmp1__" && mv "$f.__tmp1__" "$f"
  # Remove single-line az account show guard blocks: az account show ... || { ... }
  # This is simplistic and removes lines containing 'az account show' up to matching '}' on same or subsequent lines.
  awk '
    BEGIN{skip=0; depth=0}
    {
      if (skip==0 && $0 ~ /az[[:space:]]+account[[:space:]]+show/ && $0 ~ /\|\|[[:space:]]*\{/){
        skip=1; depth=1; next
      }
      if (skip==1){
        # track braces
        if ($0 ~ /\{/){ depth++ }
        if ($0 ~ /\}/){ depth-- }
        if (depth<=0){ skip=0; next }
        next
      }
      print
    }
  ' "$f" > "$f.__tmp2__" && mv "$f.__tmp2__" "$f"
  if ! bash -n "$f"; then
    mv "$bak" "$f" # restore
  else
    rm -f "$bak"
  fi
done

echo "Cleanup complete. See $REPORT"
