const base = process.argv[2] || "http://127.0.0.1:4350";

async function send(caseId: string, message: string) {
  const outRes = await fetch(`${base}/api/mortgage/chat`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ caseId, message }),
  });
  const out = await outRes.json();
  const reply = (out.messages || [])
    .filter((x: { role: string }) => x.role === "assistant")
    .pop()?.content?.slice(0, 120);
  return {
    msg: message,
    status: out.status,
    blocked: out.process?.blocked,
    loan: out.profile?.loan_balance ?? null,
    missing: out.process?.missingRequired ?? [],
    reply,
  };
}

async function main() {
  const c = await (await fetch(`${base}/api/mortgage/case`, { method: "POST" })).json();
  const caseId = c.caseId;
  const turns = [
    "My name is Pat Lee, Texas",
    "I want mortgage protection on me only",
    "I am 40 years old",
    "loan balance 180000 usd, 20 years left",
    "5 feet 8 inches, 160 pounds, non-smoker",
    "none of those",
    "annual income 75000",
  ];
  for (const m of turns) {
    const row = await send(caseId, m);
    console.log(JSON.stringify(row));
    if (row.msg.includes("180000") === false && row.loan === 180000) {
      // keep checking
    }
    if (/loan balance|still owed|how much.*(owe|loan)/i.test(row.reply || "") && row.loan === 180000) {
      console.log(JSON.stringify({ FAIL: "reasked loan", reply: row.reply }));
      process.exitCode = 1;
    }
  }
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});

export {};
