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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
source "$repo_root/scripts/lib-hypertwist-gitnexus.sh"
analysis_root="$repo_root/.gitnexus-source-only-root"
max_size_kb="${HYPERTWIST_GITNEXUS_MAX_FILE_SIZE_KB:-256}"
analysis_timeout_seconds="${HYPERTWIST_GITNEXUS_ANALYZE_TIMEOUT_SECONDS:-300}"

copy_targets=(
  "UnrealHyperTwist/Source"
  "Content/Browser/src"
  "website/src"
  "website/server/src"
  "scripts"
)

rm -rf "$analysis_root"
mkdir -p "$analysis_root"

for target in "${copy_targets[@]}"; do
  source_path="$repo_root/$target"
  if [[ ! -e "$source_path" ]]; then
    continue
  fi

  destination_path="$analysis_root/$target"
  mkdir -p "$(dirname "$destination_path")"
  cp -R "$source_path" "$destination_path"
done

find "$analysis_root" -type f -size +"${max_size_kb}"k -delete

# GitNexus status and registry behavior assume a repository root, so give the
# disposable source-only mirror its own lightweight git boundary.
git -C "$analysis_root" init -q
git -C "$analysis_root" config user.name "HyperTwist GitNexus Mirror"
git -C "$analysis_root" config user.email "hypertwist-gitnexus@local.invalid"
git -C "$analysis_root" add -A
git -C "$analysis_root" commit -q -m "source-only snapshot"

cd "$analysis_root"

run_analysis_command() {
  local -n command_ref="$1"

  if command -v timeout >/dev/null 2>&1; then
    timeout "${analysis_timeout_seconds}s" "${command_ref[@]}"
  else
    "${command_ref[@]}"
  fi
}

read_indexed_commit() {
  node -e '
    const fs = require("fs");
    const path = ".gitnexus/meta.json";
    if (!fs.existsSync(path)) {
      process.exit(1);
    }
    const meta = JSON.parse(fs.readFileSync(path, "utf8"));
    if (typeof meta.lastCommit !== "string" || meta.lastCommit.length === 0) {
      process.exit(1);
    }
    process.stdout.write(meta.lastCommit);
  ' 2>/dev/null || true
}

run_analysis_attempt() {
  local cli_kind="$1"
  shift
  local command=("$@")
  local analysis_exit_code=0

  set +e
  if [[ "$cli_kind" == "local" && "${HYPERTWIST_GITNEXUS_DEBUG_LOCAL:-0}" != "1" ]]; then
    run_analysis_command command 2>/dev/null
  else
    run_analysis_command command
  fi
  analysis_exit_code=$?
  set -e

  if [[ "$analysis_exit_code" -eq 0 ]]; then
    return 0
  fi

  local current_commit
  current_commit="$(git rev-parse HEAD)"
  local indexed_commit
  indexed_commit="$(read_indexed_commit)"

  if [[ "$analysis_exit_code" -eq 124 || "$analysis_exit_code" -eq 137 ]]; then
    if [[ -n "$indexed_commit" && "$indexed_commit" == "$current_commit" ]]; then
      echo "GitNexus analyze hit the configured timeout after indexing the current bounded mirror; treating the run as successful." >&2
      echo "Indexed commit: ${indexed_commit:0:7} (${cli_kind} CLI, timeout ${analysis_timeout_seconds}s)." >&2
      return 0
    fi
  fi

  if [[ "$cli_kind" == "local" && -n "$indexed_commit" && "$indexed_commit" == "$current_commit" ]]; then
    if node "$local_gitnexus_cli" status >/dev/null 2>&1; then
      echo "Local GitNexus analyze exited with code $analysis_exit_code after indexing the current bounded mirror, but follow-up status confirmed the fresh index; treating the run as successful." >&2
      echo "Indexed commit: ${indexed_commit:0:7} (local CLI, post-index non-zero exit)." >&2
      return 0
    fi
  fi

  if [[ -n "$indexed_commit" ]]; then
    echo "GitNexus analyze exited with code $analysis_exit_code after indexing commit ${indexed_commit:0:7}, which did not match current mirror commit ${current_commit:0:7}." >&2
  else
    echo "GitNexus analyze exited with code $analysis_exit_code before a readable bounded-mirror index result was available." >&2
  fi

  return "$analysis_exit_code"
}

local_cli_command=(
  node
  analyze
  .
  --skip-agents-md
)

npx_cli_command=(
  npx
  -y
  gitnexus@latest
  analyze
  .
  --skip-agents-md
)

local_cli_command+=("$@")
npx_cli_command+=("$@")

local_cli_available=0
if local_gitnexus_cli="$(hypertwist_gitnexus_resolve_local_cli "$repo_root")"; then
  local_cli_available=1
  local_cli_command=(
    node
    "$local_gitnexus_cli"
    analyze
    .
    --skip-agents-md
  )
fi

if [[ "$local_cli_available" -eq 1 ]]; then
  if run_analysis_attempt "local" "${local_cli_command[@]}"; then
    exit 0
  fi

  echo "Local retained GitNexus CLI passed the runtime probe but did not complete cleanly. Falling back to npx gitnexus@latest." >&2
fi

run_analysis_attempt "npx" "${npx_cli_command[@]}"
