// SPEC: PJ2026-010401 Web工作台 draft-2026-06-17-r0.
// Responsibility: Playwright fixtures for isolated Workbench fake-runtime scenarios.

import { expect, test as base, type Page, type TestInfo } from "@playwright/test";
import { selectors } from "./selectors";

export { expect };

export const test = base.extend<{ scenarioId: string }>({
  scenarioId: ["baseline", { option: true }],
  page: async ({ page, request, scenarioId }, use) => {
    const reset = await request.post("/__e2e/reset", { data: { scenarioId } });
    expect(reset.ok()).toBeTruthy();
    await expect.poll(async () => (await (await request.get("/__e2e/state")).json() as { scenarioId?: string }).scenarioId).toBe(scenarioId);
    await use(page);
  }
});

export async function gotoWorkbench(page: Page, path = "/workbench"): Promise<void> {
  await page.goto(path);
  await expect(page.locator(selectors.workspace)).toBeVisible();
  await expect(page.locator(selectors.commandInput)).toBeVisible();
}

export async function saveScreenshot(page: Page, testInfo: TestInfo, name: string): Promise<void> {
  await page.screenshot({ path: testInfo.outputPath(`${name}.png`), fullPage: true });
}

export async function fakeServerState(page: Page): Promise<Record<string, unknown>> {
  const response = await page.request.get("/__e2e/state");
  expect(response.ok()).toBeTruthy();
  return await response.json() as Record<string, unknown>;
}
