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

workspace_root="${1:-$PWD}"
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
check_script="$script_dir/check-runtime.sh"

eval "$("$script_dir/workflow-setup.sh" "$workspace_root")"

repos_path="$REPOS_FILE"
local_config_path="$LOCAL_CONFIG_FILE"
workspace_root="$(cd "$workspace_root" && pwd)"

if [ ! -f "$repos_path" ]; then
  echo "Runtime audit failed: repos config not found at $repos_path" >&2
  exit 2
fi

if [ ! -f "$local_config_path" ]; then
  echo "Runtime audit failed: local config not found at $local_config_path" >&2
  exit 2
fi

if [ ! -f "$check_script" ]; then
  echo "Runtime audit failed: check script not found: $check_script" >&2
  exit 2
fi

audit_rows="$(node -e '
const fs = require("fs");
const repos = JSON.parse(fs.readFileSync(process.argv[1], "utf8")).repos || {};
const local = JSON.parse(fs.readFileSync(process.argv[2], "utf8")).repos || {};
for (const [key, cfg] of Object.entries(repos)) {
  const pm = cfg.package_manager || "";
  if (pm !== "npm" && pm !== "pnpm") continue;
  const rel = local[key] || "";
  console.log([key, pm, rel].join("\t"));
}
' "$repos_path" "$local_config_path")"

total=0
ok=0
fail=0
skipped=0

echo "Runtime audit (npm/pnpm repos):"
echo

while IFS=$'\t' read -r repo_key package_manager repo_rel_path; do
  [ -n "$repo_key" ] || continue
  total=$((total + 1))

  if [ -z "$repo_rel_path" ]; then
    echo "[SKIP]    $repo_key ($package_manager) -> not configured in local-config"
    skipped=$((skipped + 1))
    continue
  fi

  if [ "${repo_rel_path#/}" != "$repo_rel_path" ]; then
    repo_abs_path="$repo_rel_path"
  else
    repo_abs_path="$workspace_root/$repo_rel_path"
  fi

  if [ ! -d "$repo_abs_path" ]; then
    echo "[SKIP]    $repo_key ($package_manager) -> path not found: $repo_abs_path"
    skipped=$((skipped + 1))
    continue
  fi

  if output="$(bash "$check_script" "$repo_abs_path" 2>&1)"; then
    echo "[OK]      $repo_key ($package_manager) -> $repo_abs_path"
    ok=$((ok + 1))
  else
    echo "[FAIL]    $repo_key ($package_manager) -> $repo_abs_path"
    echo "$output" | sed 's/^/          /'
    fail=$((fail + 1))
  fi
done <<< "$audit_rows"

echo
echo "Summary: total=$total ok=$ok fail=$fail skipped=$skipped"

if [ "$fail" -gt 0 ]; then
  exit 1
fi
