#!/usr/bin/env bash
# PR #31496 (fix(server): ACP form questions show titled choices).
# Claim: already-fixed. Titled `oneOf` choices and `items.enum` multi-select came with #19659 (f016a16b39);
# folding an optional `<id>__other` text companion into its single choice came with #34867 (07efa5bdac).
# The PR's one remaining difference, folding the companion into a multi-select too, was left out of #34867
# on purpose. Shows: the PR's single-choice behavior passes on main and fails on #34867's parent, and on
# the PR head a picked multi-select option plus typed text loses the option, while main keeps both.
# Needs deps installed (`vp i`) and `gh` authenticated. Run from the root of a clean t3code checkout.
set -euo pipefail

ok=1
pass() { echo "PASS  $*"; }
fail() { echo "FAIL  $*"; ok=0; }

if [ -n "$(git status --porcelain)" ]; then
  echo "refusing to run on a dirty tree"
  exit 2
fi
ORIG=$(git symbolic-ref -q --short HEAD || git rev-parse HEAD)
WORK=$(mktemp -d)
FORM=packages/provider-acp/src/server/elicitationForm.ts
TEST=packages/provider-acp/src/server/prove-pr-31496.test.ts
cleanup() {
  rm -f "$TEST"
  git checkout -q -f -- . 2>/dev/null || true
  git checkout -q -f "$ORIG"
  rm -rf "$WORK"
}
trap 'rc=$?; cleanup; [ "${PROOF_DONE:-0}" = 1 ] && exit 0; [ "$rc" -ne 0 ] && exit "$rc"; exit 1' EXIT

git fetch -q origin main
MAIN=$(git rev-parse FETCH_HEAD)
git fetch -q origin pull/31496/head
PR_HEAD=$(git rev-parse FETCH_HEAD)
FIX=07efa5bdac56be7846270eb9fafdb75a3c19cdcd
TITLED=f016a16b390f0a0237f71c691596fbd7bce43bc7
echo "main=$MAIN pr_head=$PR_HEAD fix=$FIX titled=$TITLED"

# 1. #19659 added the form parser with titled oneOf options; #34867 added the single-choice companion fold.
if git merge-base --is-ancestor "$TITLED" "$MAIN" \
  && [ "$(git log -1 --format=%s "$TITLED")" = "fix(acp): preserve native form questions and typed answers (#19659)" ] \
  && git show "$TITLED:$FORM" | grep -qF 'function titledOption(' \
  && ! git cat-file -e "$TITLED^:$FORM" 2>/dev/null; then
  pass "#19659 ($(git rev-parse --short "$TITLED")) is on main and added $FORM with titled oneOf options"
else
  fail "#19659 is not on main or did not add the titled-choice parser"
fi
if git merge-base --is-ancestor "$FIX" "$MAIN" \
  && [ "$(git log -1 --format=%s "$FIX")" = "fix(acp): ask forms with a free-text companion field show one step per question (#34867)" ] \
  && git show "$FIX:$FORM" | grep -qF 'const companionId = `${id}__other`;' \
  && ! git show "$FIX^:$FORM" | grep -qF '__other'; then
  pass "#34867 ($(git rev-parse --short "$FIX")) is on main and added the <id>__other companion fold"
else
  fail "#34867 is not on main or did not add the companion fold"
fi

# 2. The fold #34867 shipped is single-choice only; the PR head also folds multi-select.
if git show "$FIX:$FORM" | grep -qF '      field.kind === "choice" &&' \
  && git show "$PR_HEAD:$FORM" | grep -qF '(field.kind === "choice" || field.kind === "multiChoice") &&'; then
  pass "#34867 folds the companion only for a single choice; the PR head also folds it for multi-select"
else
  fail "the companion conditions on #34867 and the PR head are not as described"
fi
body=$(gh pr view 34867 --repo pingdotgg/t3code --json body --jq .body)
if printf '%s' "$body" | grep -qF 'This round narrows the fold to single-choice fields only' \
  && printf '%s' "$body" | grep -qF 'came back as text only, worse than main'; then
  pass "#34867's description says multi-select folding was removed because a mixed answer came back as text only"
else
  fail "#34867's description does not say why multi-select folding was removed"
fi

# 3. Behavioral: the PR's OMP form (its titledChoiceSchema), answered the way the shared client builds answers.
write_test() {
  cat > "$TEST" <<'EOF'
import { assert, describe, it } from "@effect/vitest";

import {
  resolvePendingUserInputAnswer,
  setPendingUserInputCustomAnswer,
  togglePendingUserInputOptionSelection,
} from "../../../client-runtime/src/state/pendingUserInput.ts";
import { parseElicitationForm } from "./elicitationForm.ts";

// The form from PR #31496's own test: OMP titled choices, each with an optional `<id>__other` companion.
const schema = {
  type: "object",
  properties: {
    q0: {
      type: "string",
      title: "Deploy the rule now?",
      description: "Global rule",
      oneOf: [
        { const: "Deploy now", title: "Deploy now", description: "Goes live after a restart." },
        { const: "Not yet", title: "Not yet" },
      ],
      default: "Deploy now",
    },
    q0__other: { type: "string", title: "Other" },
    q1: {
      type: "array",
      title: "Which harnesses?",
      items: { type: "string", enum: ["Claude", "Codex"] },
    },
    q1__other: { type: "string", title: "Other" },
  },
};

describe("prove-pr-31496", () => {
  it("prove-pr-31496 single choice: titled options, companion folded, custom text sent to it", () => {
    const form = parseElicitationForm(schema, "Your answer?");
    assert(form !== undefined);
    assert.deepStrictEqual(
      form.questions.map((question) => question.id).filter((id) => id.startsWith("q0")),
      ["q0"],
    );
    const q0 = form.questions.find((question) => question.id === "q0");
    assert(q0 !== undefined);
    assert.deepStrictEqual(q0.options, [
      { label: "Deploy now", description: "Goes live after a restart.", value: "Deploy now" },
      { label: "Not yet", description: "Not yet", value: "Not yet" },
    ]);
    assert.notStrictEqual(q0.allowCustomAnswer, false);
    const q1 = form.questions.find((question) => question.id === "q1");
    assert(q1 !== undefined);
    assert.isTrue(q1.multiSelect);
    assert.deepStrictEqual(
      q1.options.map((option) => option.value),
      ["Claude", "Codex"],
    );

    const picked = resolvePendingUserInputAnswer(
      q0,
      togglePendingUserInputOptionSelection(q0, undefined, "Not yet"),
    );
    const typed = resolvePendingUserInputAnswer(
      q0,
      setPendingUserInputCustomAnswer(q0, undefined, "Friday"),
    );
    assert(picked !== null && typed !== null);
    assert.deepStrictEqual(form.content({ q0: picked, q1: ["Claude", "Codex"] }), {
      q0: "Not yet",
      q1: ["Claude", "Codex"],
    });
    assert.deepStrictEqual(form.content({ q0: typed }), { q0__other: "Friday" });
  });

  it("prove-pr-31496 multi-select: a picked option and typed text both reach the agent", () => {
    const form = parseElicitationForm(schema, "Your answer?");
    assert(form !== undefined);
    const q1 = form.questions.find((question) => question.id === "q1");
    assert(q1 !== undefined);
    const other = form.questions.find((question) => question.id === "q1__other");
    // The user picks Codex, then types "Pi" where the form offers free text.
    const selected = togglePendingUserInputOptionSelection(q1, undefined, "Codex");
    const drafts =
      other === undefined
        ? { q1: setPendingUserInputCustomAnswer(q1, selected, "Pi") }
        : { q1: selected, q1__other: setPendingUserInputCustomAnswer(other, undefined, "Pi") };
    const answers: Record<string, string | ReadonlyArray<string>> = {};
    for (const question of form.questions) {
      const answer = resolvePendingUserInputAnswer(
        question,
        drafts[question.id as keyof typeof drafts],
      );
      if (answer !== null && question.id !== "q0") answers[question.id] = answer;
    }
    assert.deepStrictEqual(form.content(answers), { q1: ["Codex"], q1__other: "Pi" });
  });
});
EOF
}
run_test() {
  (cd packages/provider-acp && vp test run --config ../../vite.config.ts --reporter=verbose src/server/prove-pr-31496.test.ts) > "$1" 2>&1 || true
  grep -E "prove-pr-31496 (single|multi)|Tests +[0-9]|AssertionError" "$1" | sed -E 's/ +[0-9]+ms$//' | head -12 || tail -20 "$1"
}
line_ok() { grep -E "✓.*prove-pr-31496 $2" "$1" >/dev/null; }
line_failed() { grep -E "×.*prove-pr-31496 $2" "$1" >/dev/null; }

echo "--- main"
git checkout -q --detach "$MAIN"
write_test
run_test "$WORK/main.log"
if grep -qE "Tests +2 passed" "$WORK/main.log" && ! grep -qE "Tests +.*failed" "$WORK/main.log"; then
  pass "on main, the PR's form shows titled single-choice options with the companion folded, routes typed text to q0__other, and keeps a multi-select option plus typed text"
else
  fail "the cases did not both pass on main"
fi
rm -f "$TEST"

echo "--- #34867's parent"
git checkout -q --detach "$FIX^"
write_test
run_test "$WORK/parent.log"
if line_failed "$WORK/parent.log" "single" \
  && grep -qF "expected [ 'q0', 'q0__other' ] to deeply equal [ 'q0' ]" "$WORK/parent.log"; then
  pass "on #34867's parent ($(git rev-parse --short "$FIX^")), the single-choice case fails: q0__other is asked as its own question"
else
  fail "the single-choice case did not fail on #34867's parent"
fi
rm -f "$TEST"

echo "--- PR head"
git checkout -q --detach "$PR_HEAD"
write_test
run_test "$WORK/head.log"
if line_ok "$WORK/head.log" "single" && line_failed "$WORK/head.log" "multi" \
  && grep -qF "expected { q1: [], q1__other: 'Pi' } to deeply equal { q1: [ 'Codex' ], q1__other: 'Pi' }" "$WORK/head.log"; then
  pass "on the PR head, the single-choice case passes as on main, and the multi-select case fails: the picked Codex is dropped (q1: [])"
else
  fail "the PR head did not pass the single-choice case and drop the picked multi-select option"
fi
rm -f "$TEST"

if [ "$ok" = 1 ]; then
  echo "VERDICT: CLOSE (already-fixed) - main has the PR's titled choices (#19659) and single-choice companion fold (#34867); its only extra, a multi-select fold, drops a picked option"
  PROOF_DONE=1; exit 0
fi
echo "VERDICT: KEEP - at least one check failed"
exit 1
