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

script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd -- "${script_dir}/.." && pwd)"
cd "${repo_root}"

tmp_file="$(mktemp)"
trap 'rm -f "${tmp_file}"' EXIT

rg -n -o '(?:/docs|docs)/[a-z0-9_/-]+\.md' \
  README.md docs .agents \
  -g '*.md' \
  -g '!.agents/runs/**' \
  > "${tmp_file}" || true

missing=0
while IFS= read -r line; do
  file="${line%%:*}"
  rest="${line#*:}"
  line_no="${rest%%:*}"
  ref="${rest#*:}"
  normalized="${ref#/}"

  if [[ ! -f "${normalized}" ]]; then
    printf '%s:%s -> %s\n' "${file}" "${line_no}" "${ref}"
    missing=1
  fi
done < "${tmp_file}"

if [[ ${missing} -ne 0 ]]; then
  echo "[FAIL] broken docs links found"
  exit 1
fi

echo "[OK] docs links resolve (.agents/runs/** excluded by default)"
