import { expect, test } from "@playwright/test";
import { MP_CHAT_API, type MpGolden } from "../mp-golden";
import { createCase, sendMany, type CaseJson } from "./helpers";

function check(c: MpGolden, out: CaseJson): string[] {
  const issues: string[] = [];
  if (c.profile) {
    for (const [k, v] of Object.entries(c.profile)) {
      const actual = out.profile[k];
      if (JSON.stringify(actual) !== JSON.stringify(v)) issues.push(`${k}: expected ${JSON.stringify(v)} got ${JSON.stringify(actual)}`);
    }
  }
  for (const k of c.absent || []) {
    if (out.profile[k]) issues.push(`${k} should be absent, got ${JSON.stringify(out.profile[k])}`);
  }
  if (c.screens) {
    const screens = (out.profile.disease_screens || {}) as Record<string, string>;
    for (const [k, v] of Object.entries(c.screens)) {
      if (screens[k] !== v) issues.push(`screen ${k}: expected ${v} got ${screens[k]}`);
    }
  }
  if (c.step != null && out.process.step !== c.step) issues.push(`step: expected ${c.step} got ${out.process.step}`);
  for (const m of c.missingIncludes || []) {
    if (!out.process.missingRequired.includes(m)) issues.push(`missingRequired lacks ${m}`);
  }
  if (c.statusNot && out.status === c.statusNot) issues.push(`status should not be ${c.statusNot}`);
  if (c.stopPath === null && out.stopPath) issues.push(`stopPath should be empty, got ${out.stopPath}`);
  if (c.stopPath && out.stopPath !== c.stopPath) issues.push(`stopPath: expected ${c.stopPath} got ${out.stopPath}`);
  const reply = out.messages.filter((m) => m.role === "assistant").at(-1)?.content || "";
  if (c.replyMatch && !new RegExp(c.replyMatch, "i").test(reply)) issues.push(`reply missing /${c.replyMatch}/: ${reply.slice(0, 160)}`);
  if (c.replyNotMatch && new RegExp(c.replyNotMatch, "i").test(reply)) issues.push(`reply leaked /${c.replyNotMatch}/`);
  return issues;
}

test("MP-001–200 Chat-API catalog (heuristic, DISABLE_CHAT_MODEL=1)", async ({ request }) => {
  test.setTimeout(180_000);
  const failures: string[] = [];
  for (const c of MP_CHAT_API) {
    const created = await createCase(request);
    const out = await sendMany(request, created.caseId, c.messages);
    const issues = check(c, out);
    if (issues.length) failures.push(`${c.id}: ${issues.join("; ")}`);
  }
  expect(failures, failures.join("\n")).toEqual([]);
});
