#!/bin/sh
# SPDX-License-Identifier: AGPL-3.0-or-later

set -eu

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
PROJECT_ROOT=$(dirname -- "$SCRIPT_DIR")

cd "$PROJECT_ROOT"

if [ -x "$PROJECT_ROOT/.venv/bin/python" ]; then
    PYTHON="$PROJECT_ROOT/.venv/bin/python"
elif command -v python3 >/dev/null 2>&1; then
    PYTHON=$(command -v python3)
else
    printf '%s\n' "error: python3 is required" >&2
    exit 127
fi

if [ -x "$PROJECT_ROOT/.venv/bin/pymarkdown" ]; then
    PYMARKDOWN="$PROJECT_ROOT/.venv/bin/pymarkdown"
elif command -v pymarkdown >/dev/null 2>&1; then
    PYMARKDOWN=$(command -v pymarkdown)
else
    printf '%s\n' "error: pymarkdown is required; install requirements-dev.txt" >&2
    exit 127
fi

if ! command -v lychee >/dev/null 2>&1; then
    printf '%s\n' "error: lychee is required to validate documentation links" >&2
    exit 127
fi

printf '%s\n' "Checking table formatting..."
if rg -n --fixed-strings '| |---' "$PROJECT_ROOT" --iglob '*.md' | grep -v '^\.venv/'; then
    printf '%s\n' "error: collapsed table found" >&2
    exit 1
fi

awk '
FNR == 1 { delete lines; check_pending = 0 }
{
    if (check_pending && $0 ~ /^\|[[:space:]|:-]+\|$/) {
        prev = FNR - 2
        if (prev < 1 || lines[prev] !~ /^[[:space:]]*$/) {
            printf "error: table header at line %d not preceded by blank line\n", FNR - 1 > "/dev/stderr"
            exit 1
        }
    }
    lines[FNR] = $0
    if ($0 !~ /^\|/) { check_pending = 0; next }
    if ($0 ~ /^\|[[:space:]|:-]+\|$/) { check_pending = 0; next }
    check_pending = 1
}
' "$PROJECT_ROOT"/docs/*.md "$PROJECT_ROOT"/*.md

printf '%s\n' "Verifying generated tables..."
"$PYTHON" "$PROJECT_ROOT/scripts/tables.py"

printf '%s\n' "Linting Markdown..."
"$PYMARKDOWN" --strict-config scan .

printf '%s\n' "Checking documentation links..."
lychee --include-fragments --no-progress "**/*.md"