/**
 * Verify business context draft seeding + confirm unlocks generation gate.
 * Usage: npx tsx scripts/browser-business-context-e2e.ts [baseUrl]
 */
import { chromium, type Page } from "playwright";

const base = process.argv[2] ?? "http://127.0.0.1:3056";

async function auth(page: Page) {
  await page.request.post(`${base}/api/auth/demo`);
  await page.goto(`${base}/dashboard`, { waitUntil: "domcontentloaded" });
  await page
    .waitForResponse((r) => r.url().includes("/api/projects") && r.status() === 200, {
      timeout: 20000,
    })
    .catch(() => {});
  await page.waitForTimeout(1000);
}

async function main() {
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage();
  const errors: string[] = [];
  page.on("pageerror", (e) => errors.push(e.message));

  await auth(page);

  // Simulate legacy server data: no businessContext
  const seeded = await page.evaluate(() => {
    const raw = localStorage.getItem("postsync-projects");
    if (!raw) return { ok: false, reason: "no storage" };
    const data = JSON.parse(raw);
    const pid = data.state?.activeProjectId;
    const scoped = data.state?.dataByProjectId?.[pid];
    if (!scoped?.context) return { ok: false, reason: "no context" };
    delete scoped.context.businessContext;
    if (scoped.context.businessContext !== undefined) {
      return { ok: false, reason: "delete failed" };
    }
    localStorage.setItem("postsync-projects", JSON.stringify(data));
    return { ok: true, projectId: pid };
  });

  console.log("Legacy strip businessContext:", seeded);

  await page.goto(`${base}/posting-context`, { waitUntil: "domcontentloaded" });
  await page
    .waitForResponse((r) => r.url().includes("/api/projects") && r.status() === 200, {
      timeout: 15000,
    })
    .catch(() => {});
  await page.waitForTimeout(2500);

  const body1 = await page.locator("body").innerText();
  if (body1.includes("Application error")) {
    console.log("FAIL\tpage crashed");
    console.log(errors.join("\n"));
    await browser.close();
    process.exit(1);
  }

  const hasPanel = body1.includes("This is what we understand about your business");
  const hasConfirmBtn = await page.getByRole("button", { name: /Confirm business context/i }).count();
  console.log(`${hasPanel ? "PASS" : "FAIL"}\tbusiness context panel visible`);
  console.log(`${hasConfirmBtn ? "PASS" : "FAIL"}\tconfirm button present`);

  // Try generate before confirm — should show guidance error
  const genBtn = page.getByRole("button", { name: /Generate from context/i }).first();
  if (await genBtn.count()) {
    await genBtn.click();
    await page.waitForTimeout(800);
    const errBefore = await page.locator("body").innerText();
    const blocked = errBefore.includes("not confirmed") || errBefore.includes("Confirm business context");
    console.log(`${blocked ? "PASS" : "FAIL"}\tgeneration blocked before confirm`);
  }

  // Confirm business context
  if (hasConfirmBtn) {
    await page.getByRole("button", { name: /Confirm business context/i }).click();
    await page.waitForTimeout(2000);
  }

  const confirmed = await page.evaluate(() => {
    const raw = localStorage.getItem("postsync-projects");
    if (!raw) return false;
    const data = JSON.parse(raw);
    const pid = data.state?.activeProjectId;
    return Boolean(data.state?.dataByProjectId?.[pid]?.context?.businessContext?.confirmed);
  });
  console.log(`${confirmed ? "PASS" : "FAIL"}\tbusinessContext.confirmed=true after click`);

  // Save context
  const saveBtn = page.getByRole("button", { name: /^Save Context$/i });
  if (await saveBtn.count()) {
    await saveBtn.click();
    await page.waitForTimeout(2000);
  }

  // Live generation should not show confirm error (may fail for other reasons)
  await page.goto(`${base}/live-generation`, { waitUntil: "domcontentloaded" });
  await page.waitForTimeout(2000);
  const genNow = page.getByRole("button", { name: /Generate Now/i }).first();
  if (await genNow.count()) {
    await genNow.click();
    await page.waitForTimeout(3000);
    const body2 = await page.locator("body").innerText();
    const stillBlocked = body2.includes("not confirmed") || body2.includes("Confirm business context");
    console.log(`${stillBlocked ? "FAIL" : "PASS"}\tlive generation not blocked by confirm gate`);
  }

  console.log(`\nPage errors: ${errors.length ? errors.join("; ") : "(none)"}`);
  await browser.close();
  process.exit(confirmed ? 0 : 1);
}

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