#!/usr/bin/env bash
# Behavior test against fixture repos only; never a real checkout.
set -euo pipefail

REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
ADOPTER="$REPO/modules/workstation/claude/bin/adopt-owner-edits"
WORK="$(mktemp -d "$REPO/.adopt-owner-fixture.XXXXXX")"
trap 'rm -rf "$WORK"' EXIT
fail() { printf 'FAIL %s\n' "$1" >&2; exit 1; }

export GIT_AUTHOR_NAME=t GIT_AUTHOR_EMAIL=t@t GIT_COMMITTER_NAME=t GIT_COMMITTER_EMAIL=t@t
git init --quiet --bare "$WORK/origin.git"
git clone --quiet "$WORK/origin.git" "$WORK/co" 2>/dev/null
cd "$WORK/co"
git checkout --quiet -b main
mkdir -p docs/plans .claude modules/workstation/claude apps/web/src
echo v1 > docs/plans/plan.md
echo '{"a":1}' > .claude/settings.json
echo landed > docs/landed.md
echo 'export {}' > apps/web/src/code.tsx
echo seed > modules/workstation/claude/seed.md
git add -A && git commit --quiet -m init && git push --quiet origin main

# Owner dirt: edited plan, new skill doc, edited config. Agent dirt: code file.
echo v2 > docs/plans/plan.md
mkdir -p modules/workstation/claude/skills/newskill
echo skill > modules/workstation/claude/skills/newskill/SKILL.md
echo '{"a":2}' > .claude/settings.json
echo 'export {} // stray' > apps/web/src/code.tsx
echo lock > bun.lock
# scratch workspace: md files inside an unknown top-level dir are never adopted
mkdir -p temp-user/notes
echo scratch > temp-user/notes/scratch.md
# stale duplicate: identical to landed content
echo landed > docs/landed.md

out=$(bash "$ADOPTER" "$WORK/co") || fail "adopter exited nonzero: $out"
case "$out" in *"landed "*) ;; *) fail "no landed receipt in: $out";; esac

check=$(git --git-dir "$WORK/origin.git" show main:docs/plans/plan.md)
[ "$check" = v2 ] || fail "edited plan not landed"
git --git-dir "$WORK/origin.git" cat-file -e main:modules/workstation/claude/skills/newskill/SKILL.md \
  || fail "new skill doc not landed"
check=$(git --git-dir "$WORK/origin.git" show main:.claude/settings.json)
[ "$check" = '{"a":2}' ] || fail "config edit not landed"
git --git-dir "$WORK/origin.git" show main:apps/web/src/code.tsx | grep -q stray \
  && fail "source code was adopted" || true
git --git-dir "$WORK/origin.git" cat-file -e main:bun.lock 2>/dev/null \
  && fail "lockfile was adopted" || true
git --git-dir "$WORK/origin.git" cat-file -e main:temp-user/notes/scratch.md 2>/dev/null \
  && fail "scratch-dir markdown was adopted" || true

# Second run: everything owner-kind now matches origin — nothing to adopt.
out=$(bash "$ADOPTER" "$WORK/co") || fail "rerun exited nonzero"
case "$out" in *"nothing to adopt"*) ;; *) fail "rerun adopted again: $out";; esac

# Dirt stays in place — adoption never discards the owner's working files.
[ "$(cat apps/web/src/code.tsx)" = 'export {} // stray' ] || fail "agent dirt was touched"
[ "$(cat docs/plans/plan.md)" = v2 ] || fail "owner file content changed locally"

printf 'PASS adopt-owner-edits behavior\n'
