#!/bin/bash
#
# Logic self-check for .extras/test-build. Covers the pure, host-side parts:
# dependency resolution, override application, unknown-dep -> UNMET, cache
# decisions, and BLOCKED-BY-DEP propagation. No docker.
#
# Run: bash .extras/test-logic.sh
#
set -uo pipefail

SCRIPT="$(dirname "$0")/test-build"
T=$(mktemp -d)
BASE_DB=$(mktemp -d); mkdir -p "$BASE_DB"

cleanup() { rm -rf "$T" "$BASE_DB"; }
trap cleanup EXIT

# Source the script without running main(). Sourcing re-runs the CONFIG block,
# so set test vars AFTER the source.
LIB=$(mktemp)
sed '/^main "\$@"$/d' "$SCRIPT" > "$LIB"
# shellcheck disable=SC1090
source "$LIB" 2>/dev/null
rm -f "$LIB"

pass=0; fail=0
ok()  { echo "  ok: $1"; ((pass++)); return 0; }
bad() { echo "  FAIL: $1"; ((fail++)); return 0; }

# Placeholder assertion so this file runs before any logic exists.
ok "script sources without executing main"

# --- version selection ------------------------------------------------------
SBO_TREE_CURRENT="/trees/current"
SBO_TREE_STABLE="/trees/stable"
IMAGE_CURRENT="sbo-testbuild:current"
IMAGE_STABLE="sbo-testbuild:15.0"

VERSION_ID="current"; select_version_paths
[[ "$ACTIVE_TREE" == "/trees/current" ]] && ok "current -> current tree" || bad "current tree wrong: [$ACTIVE_TREE]"
[[ "$ACTIVE_IMAGE" == "sbo-testbuild:current" ]] && ok "current -> current image" || bad "current image wrong: [$ACTIVE_IMAGE]"

VERSION_ID="15.0"; select_version_paths
[[ "$ACTIVE_TREE" == "/trees/stable" ]] && ok "15.0 -> stable tree" || bad "stable tree wrong: [$ACTIVE_TREE]"
[[ "$ACTIVE_IMAGE" == "sbo-testbuild:15.0" ]] && ok "15.0 -> stable image" || bad "stable image wrong: [$ACTIVE_IMAGE]"

# --- resolution -------------------------------------------------------------
# Fake SBo tree under one category. mk <prog> "<REQUIRES>".
mk() { mkdir -p "$T/cat/$1"; echo "REQUIRES=\"$2\"" > "$T/cat/$1/$1.info"; }
mk c ""
mk b "c"
mk a "b %README%"
mk d "nonexistentpkg"
mk e "f"
mk f "e"
mk g "b"

SBO_TREE_ROOTS=("$T")   # resolver reads this global (set by select in real runs)

resolve_target "$T/cat/a"
order=""; for x in "${RESOLVED_ORDER[@]}"; do order+="$(basename "$x") "; done
order="${order% }"
[[ "$order" == "c b a" ]] && ok "topo order c b a" || bad "topo order, got: [$order]"
[[ "${HAS_README[$T/cat/a]:-}" == "1" ]] && ok "%README% recorded" || bad "%README% not recorded"
[[ ${#UNMET[@]} -eq 0 ]] && ok "no false unmet" || bad "unexpected unmet"

resolve_target "$T/cat/d"
[[ ${#UNMET[@]} -eq 1 ]] && ok "unmet-dep caught" || bad "unmet-dep missed"

resolve_target "$T/cat/e"
[[ ${#CYCLES[@]} -ge 1 ]] && ok "cycle caught" || bad "cycle missed"

echo
echo "$pass passed, $fail failed"
[[ $fail -eq 0 ]] || exit 1
echo "ALL LOGIC CHECKS PASS"
