"use strict";

const { chromium } = require("playwright");
const {
  BASE_URL,
  MNOTE_WEB_BASE_URL,
  UI_TIMEOUT_MS,
  assert,
  cleanupDocuments,
  ensureAuthenticated,
  openDocument,
  prepareTempTreeFixture,
  requireMnoteWebSmokeBaseUrl,
} = require("./tree-shell-smoke-helpers");

async function runDefaultShellPath(page, fixture) {
  await openDocument(page, fixture.workspaceId, fixture.parentId);

  await page.getByRole("button", { name: "进入编辑" }).waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  assert(
    (await page.locator(`iframe[title="mnote-web-document-shell-${fixture.parentId}"]`).count()) === 0,
    "默认文档页不应继续挂载 mnote-web 文档壳 iframe",
  );
  await page.getByRole("button", { name: "进入编辑" }).click({ timeout: UI_TIMEOUT_MS });
  await page.getByLabel("页面标题").waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await page.locator(".wolai-editor").first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });

  return {
    compatReady: true,
  };
}

async function runRuntimeDebugPath(page, fixture) {
  const runtimeBaseUrl = requireMnoteWebSmokeBaseUrl();
  await page.goto(`${BASE_URL}/api/auth/mnote-web-token`, { waitUntil: "commit", timeout: UI_TIMEOUT_MS });
  await page.goto(
    `${runtimeBaseUrl}/document-debug?documentId=${fixture.parentId}&workspaceId=${fixture.workspaceId}&host=task103-smoke`,
    { waitUntil: "commit", timeout: UI_TIMEOUT_MS },
  );
  await page.getByText("Document Runtime Debug").waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await page.locator("#block-editor-list").waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await page.locator("#editor-command-slash").waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });

  return {
    debugUrl: page.url(),
  };
}

async function main() {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({
    viewport: { width: 1440, height: 960 },
  });
  const page = await context.newPage();

  let caughtError = null;
  let fixture = null;

  try {
    const viewer = await ensureAuthenticated(page, context.request);
    fixture = await prepareTempTreeFixture(context.request);

    const primary = await runDefaultShellPath(page, fixture);
    const debug = await runRuntimeDebugPath(page, fixture);

    console.log(
      JSON.stringify(
        {
          ok: true,
          baseUrl: BASE_URL,
          viewerUserId: viewer.userId,
          workspaceId: fixture.workspaceId,
          parentId: fixture.parentId,
          childId: fixture.childId,
          debugRuntimeBaseUrl: MNOTE_WEB_BASE_URL || null,
          primary,
          debug,
        },
        null,
        2,
      ),
    );
  } catch (error) {
    caughtError = error;
  } finally {
    if (fixture) {
      try {
        await cleanupDocuments(context.request, fixture.createdIds);
      } catch (cleanupError) {
        if (!caughtError) {
          caughtError = cleanupError;
        } else {
          console.error(
            `清理临时页面失败：${
              cleanupError instanceof Error
                ? cleanupError.stack || cleanupError.message
                : String(cleanupError)
            }`,
          );
        }
      }
    }
    await page.close().catch(() => undefined);
    await context.close().catch(() => undefined);
    await browser.close().catch(() => undefined);
  }

  if (caughtError) {
    throw caughtError;
  }
}

main().catch((error) => {
  console.error(error instanceof Error ? error.stack || error.message : String(error));
  process.exit(1);
});
