#!/usr/bin/env bash
# Verify the endpoint-libs dependency chain is internally consistent.
#
# Graph checks preserve existing lockfiles and clean up locks they create.
#
#   ./scripts/check-chain.sh            # check everything
#   ./scripts/check-chain.sh --quick    # skip builds, tests and feature checks
#
# Exits non-zero if anything is inconsistent. See docs/chain.md for why each of
# these matters, and docs/release-order.md for the release runbook.

set -uo pipefail

CODE_ROOT="${CODE_ROOT:-$(cd "$(dirname "$0")/../.." && pwd)}"
QUICK=false
[[ "${1:-}" == "--quick" ]] && QUICK=true

TOOLS=(endpoint-libs EndpointGen honey_id-types EndpointValidator)
BACKENDS=(api.support.cafe web3.trading-backend nofilter.io-backend
          merchant.pays.online auth.honey.id-backend api.honey.id-backend)

FAILURES=0
pass() { printf '  \033[32m✓\033[0m %s\n' "$1"; }
fail() { printf '  \033[31m✗\033[0m %s\n' "$1"; FAILURES=$((FAILURES + 1)); }
skip() { printf '  \033[33m-\033[0m %s\n' "$1"; }
head_() { printf '\n\033[1m%s\033[0m\n' "$1"; }

repo() {
    local name=$1
    if [[ "$name" == EndpointGen && ! -d "$CODE_ROOT/$name" ]]; then
        name=endpointgen
    fi
    printf '%s\n' "$CODE_ROOT/$name"
}
have() { [[ -d "$(repo "$1")" ]]; }

# ── Dependency graphs ───────────────────────────────────────────────────────
# A workspace lockfile combines member resolutions. Check members separately
# so EndpointValidator's intentional ws-load-test split does not fail.
graph_tree() {
    local output
    if output=$(cargo tree --locked --offline --color never --prefix none --format '{p}' "$@" 2>/dev/null); then
        printf '%s\n' "$output"
    else
        cargo tree --locked --color never --prefix none --format '{p}' "$@"
    fi
}

check_workspace() (
    r=$1
    FAILURES=0
    cd "$(repo "$r")" || { fail "$r: could not enter checkout"; exit 1; }
    manifest=$(cargo locate-project --workspace --message-format plain) ||
        { fail "$r: could not locate Cargo workspace"; exit 1; }
    lock="${manifest%/*}/Cargo.lock"
    if [[ ! -e "$lock" && ! -L "$lock" ]]; then
        # Reserve the path without clobbering another writer. Cargo preserves
        # the leading comment, so cleanup can recognize the lock we created.
        marker="# check-chain temporary lock $$-$RANDOM-$RANDOM"
        trap '
            if [[ -e "$lock" || -L "$lock" ]]; then
                if [[ -f "$lock" && ! -L "$lock" ]] && grep -Fxq -- "$marker" "$lock"; then
                    rm -- "$lock" || exit 1
                else
                    fail "$r: lock ownership could not be verified; left $lock in place"
                    exit 1
                fi
            fi
        ' EXIT
        trap 'exit 129' HUP
        trap 'exit 130' INT
        trap 'exit 143' TERM
        if ! (set -C; printf '%s\n' '# This file is automatically @generated by Cargo.' \
            '# It is not intended for manual editing.' "$marker" > "$lock"); then
            fail "$r: could not reserve $lock"
            exit 1
        fi
        cargo generate-lockfile || { fail "$r: could not generate Cargo.lock"; exit 1; }
    elif [[ ! -f "$lock" ]]; then
        fail "$r: $lock is not a regular file"
        exit 1
    fi

    if ! members=$(graph_tree --workspace --depth 0 | sed -nE 's/^([^ ]+) v[0-9].*/\1/p') || [[ -z "$members" ]]; then
        fail "$r: could not list workspace members"
        exit 1
    fi
    for member in $members; do
        if ! packages=$(graph_tree -p "$member" | sed -nE 's/ \(\*\)$//; /^endpoint-libs v[0-9]/p' | sort -u); then
            fail "$r/$member: could not resolve dependency graph"
        elif [[ "$packages" == *$'\n'* ]]; then
            fail "$r/$member resolves multiple endpoint-libs packages: ${packages//$'\n'/, }"
        elif [[ -n "$packages" ]]; then
            pass "$r/$member resolves $packages"
        else
            skip "$r/$member does not depend on endpoint-libs"
        fi
    done
    (( FAILURES == 0 ))
)

head_ "One endpoint-libs per graph"
for r in "${TOOLS[@]}" "${BACKENDS[@]}"; do
    have "$r" || { skip "$r (not checked out)"; continue; }
    check_workspace "$r" || FAILURES=$((FAILURES + 1))
done

# ── Generator compatibility and artifact drift ──────────────────────────────
# --check validates version.toml against the installed binary's requirements
# before checking the generated artifacts.
head_ "Generator compatibility and generated docs (endpoint-gen --check)"
for r in "${BACKENDS[@]}"; do
    have "$r" || { skip "$r (not checked out)"; continue; }
    if out=$(cd "$(repo "$r")" && endpoint-gen --config-dir config --check 2>&1); then
        pass "$r: ${out##*: }"
    else
        fail "$r: $out"
    fi
done

# ── Each tool repo builds and tests ───────────────────────────────────────
if $QUICK; then
    head_ "Build & test"
    skip "--quick: skipped"
else
    head_ "Build & test"
    for r in "${TOOLS[@]}"; do
        have "$r" || { skip "$r (not checked out)"; continue; }
        if (cd "$(repo "$r")" && cargo test --quiet >/dev/null 2>&1); then
            pass "$r tests pass"
        else
            fail "$r: cargo test failed — run it there for detail"
        fi
    done
fi

# ── Every endpoint-libs feature compiles standalone ───────────────────────
# A consumer picks features one at a time, so every feature has to declare the
# dependencies its own code names. `signal` and `log_reader` did not, and it
# stayed invisible because nothing ever built them without `types`. The feature
# list lives in Cargo.toml, not in a script, so this cannot go stale.
head_ "Every endpoint-libs feature standalone"
if $QUICK; then
    skip "--quick: skipped"
elif ! have endpoint-libs; then
    skip "endpoint-libs (not checked out)"
else
    if out=$("$(repo endpoint-libs)/scripts/check-features.sh" 2>&1); then
        pass "every feature compiles alone"
    else
        fail "some features do not compile alone; run ./scripts/check-features.sh in endpoint-libs"
        echo "$out" | grep -a 'FAIL' | sed 's/^/    /'
    fi
fi

# ── Local versions vs crates.io ───────────────────────────────────────────
# Informational: an unpublished local bump is normal mid-release, but you should
# know it is the case rather than discover it from a consumer.
head_ "Local version vs crates.io"
for r in endpoint-libs EndpointGen honey_id-types; do
    have "$r" || { skip "$r (not checked out)"; continue; }
    name=$(awk '/^\[package\]/{f=1;next} f&&/^name/{gsub(/[" ]/,"");sub(/name=/,"");print;exit}' "$(repo "$r")/Cargo.toml")
    local_v=$(awk '/^\[package\]/{f=1;next} f&&/^version/{gsub(/[" ]/,"");sub(/version=/,"");print;exit}' "$(repo "$r")/Cargo.toml")
    pub_v=$(cargo search "$name" --limit 1 2>/dev/null | head -1 | sed 's/.*= "//;s/".*//')
    if [[ "$local_v" == "$pub_v" ]]; then
        pass "$name $local_v published"
    else
        skip "$name local $local_v, crates.io $pub_v (unpublished bump)"
    fi
done

# ── Result ───────────────────────────────────────────────────────────────────
echo
if (( FAILURES == 0 )); then
    printf '\033[32mChain is consistent.\033[0m\n'
    exit 0
fi
printf '\033[31m%d inconsistency(ies).\033[0m See docs/chain.md.\n' "$FAILURES"
exit 1
