#!/usr/bin/env bash
# Source roots are canonical, not module-relative: a repo-sourced item resolves to the
# same absolute path whichever copy of engine.mjs is loaded, honours OVERDECK_REPO_DIR,
# and still yields to an explicit options.repoRoot. Deploy-sourced items use the canonical
# deploy clone when OVERDECK_DEPLOY_DIR is empty.
set -uo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

unset OVERDECK_REPO_DIR OVERDECK_DEPLOY_DIR

pass=0
fail=0
ok() { pass=$((pass + 1)); printf 'PASS %s\n' "$1"; }
bad() { fail=$((fail + 1)); printf 'FAIL %s\n' "$1"; }

# A displaced copy of the engine: real files under a different tree root, with the
# sibling modules/ dependency symlinked so imports still resolve. Only import.meta.url
# differs from the in-repo copy.
DISPLACED="$TMP/displaced"
mkdir -p "$DISPLACED"
cp -r "$ROOT/lib" "$DISPLACED/lib"
ln -s "$ROOT/modules" "$DISPLACED/modules"

PROBE="$TMP/probe.mjs"
cat >"$PROBE" <<'JS'
// argv: <engine path> <source kind> [repoRoot override]
const [enginePath, kind, repoRootOverride] = process.argv.slice(2);
const { auditNode } = await import(enginePath);

const item = {
  id: `probe:${kind}`,
  source: { kind, path: "modules/workstation/bin/deck-sudo", ref: null },
  destination: "~/.local/bin/deck-sudo-probe",
  ownership: "user",
  strategy: "symlink",
  content_digest: null,
  owner: "fleet",
};

const transport = { name: "local", read: async () => ({ exists: false }) };
const options = repoRootOverride ? { repoRoot: repoRootOverride } : {};
const report = await auditNode("workstation", [item], transport, options);
const drift = report.drift.find((entry) => entry.field === "link_target");
process.stdout.write(`${drift ? drift.want : "NONE"}\n`);
JS

probe() { # $1 = engine path, $2 = source kind, $3 = optional repoRoot override
  node "$PROBE" "$1" "$2" "${3:-}"
}

HERE="$ROOT/lib/fleet/engine.mjs"
THERE="$DISPLACED/lib/fleet/engine.mjs"

# 1. Location independence: the same repo-sourced item resolves identically from both copies.
here_want="$(probe "$HERE" repo)"
there_want="$(probe "$THERE" repo)"
if [[ -n "$here_want" && "$here_want" == "$there_want" ]]; then
  ok "repo source path is identical from both module locations ($here_want)"
else
  bad "repo source path depends on module location: here=$here_want there=$there_want"
fi
case "$there_want" in
  "$DISPLACED"/*) bad "displaced copy resolved into its own tree: $there_want" ;;
  *) ok "displaced copy does not resolve into its own tree" ;;
esac

# 2. Default repo root is the canonical checkout.
default_want="$(HOME="$HOME" probe "$HERE" repo)"
if [[ "$default_want" == "$HOME/Projects/overdeck/modules/workstation/bin/deck-sudo" ]]; then
  ok "default repo root is \$HOME/Projects/overdeck"
else
  bad "default repo root wrong: $default_want"
fi

# 3. OVERDECK_REPO_DIR overrides the default, from either module location.
env_root="$TMP/fake-repo"
env_here="$(OVERDECK_REPO_DIR="$env_root" probe "$HERE" repo)"
env_there="$(OVERDECK_REPO_DIR="$env_root" probe "$THERE" repo)"
if [[ "$env_here" == "$env_root/modules/workstation/bin/deck-sudo" \
   && "$env_there" == "$env_here" ]]; then
  ok "OVERDECK_REPO_DIR overrides the default"
else
  bad "OVERDECK_REPO_DIR ignored: here=$env_here there=$env_there"
fi

# 4. options.repoRoot still wins over the env var.
opt_root="$TMP/explicit-repo"
opt_want="$(OVERDECK_REPO_DIR="$env_root" probe "$HERE" repo "$opt_root")"
if [[ "$opt_want" == "$opt_root/modules/workstation/bin/deck-sudo" ]]; then
  ok "options.repoRoot wins over OVERDECK_REPO_DIR"
else
  bad "options.repoRoot did not win: $opt_want"
fi

# 5. Deploy-sourced items are unaffected by repo-root resolution.
deploy_root="$TMP/fake-deploy"
deploy_here="$(OVERDECK_DEPLOY_DIR="$deploy_root" OVERDECK_REPO_DIR="$env_root" \
  probe "$HERE" deploy "$opt_root")"
deploy_there="$(OVERDECK_DEPLOY_DIR="$deploy_root" OVERDECK_REPO_DIR="$env_root" \
  probe "$THERE" deploy "$opt_root")"
if [[ "$deploy_here" == "$deploy_root/modules/workstation/bin/deck-sudo" \
   && "$deploy_there" == "$deploy_here" ]]; then
  ok "deploy source path is unaffected by repo-root resolution"
else
  bad "deploy source path disturbed: here=$deploy_here there=$deploy_there"
fi

# 6. An exported empty deploy root still resolves to the canonical deploy clone.
default_deploy="$(OVERDECK_DEPLOY_DIR='' probe "$HERE" deploy)"
if [[ "$default_deploy" == "$HOME/.local/share/overdeck/deploy/modules/workstation/bin/deck-sudo" ]]; then
  ok "empty OVERDECK_DEPLOY_DIR uses the canonical deploy clone"
else
  bad "empty OVERDECK_DEPLOY_DIR produced a relative source: $default_deploy"
fi

printf 'roots: pass=%d fail=%d\n' "$pass" "$fail"
[[ $fail -eq 0 ]]
