#!/usr/bin/env node
"use strict";

const assert = require("node:assert/strict");
const fs = require("node:fs");
const http = require("node:http");
const net = require("node:net");
const os = require("node:os");
const path = require("node:path");
const { spawn } = require("node:child_process");
const { chromium } = require("playwright");

const TASK = "task499-sidebar-tree-view-state-smoke";
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 45_000);
const TEST_PASSWORD = process.env.MNOTE_E2E_PASSWORD || ["Mnote", "E2E", "123!"].join("");
const RESULT_DIR = path.join(__dirname, "..", "tmp", TASK);

function resolveChromiumExecutablePath() {
  const explicit = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH || "";
  if (explicit && fs.existsSync(explicit)) return explicit;
  return [
    "/usr/bin/google-chrome-stable",
    "/usr/bin/google-chrome",
    "/snap/bin/chromium",
    "/usr/bin/chromium",
    "/usr/bin/chromium-browser",
  ].find((candidate) => fs.existsSync(candidate)) || "";
}

function pickPort() {
  return new Promise((resolve, reject) => {
    const server = net.createServer();
    server.listen(0, "127.0.0.1", () => {
      const address = server.address();
      const port = address && typeof address === "object" ? address.port : 0;
      server.close(() => resolve(port));
    });
    server.on("error", reject);
  });
}

function waitForHttpOk(url, timeoutMs) {
  const deadline = Date.now() + timeoutMs;
  return new Promise((resolve, reject) => {
    const retry = () => {
      if (Date.now() > deadline) {
        reject(new Error(`server_not_ready: ${url}`));
        return;
      }
      setTimeout(tick, 250);
    };
    const tick = () => {
      const request = http.get(url, (response) => {
        response.resume();
        if (response.statusCode >= 200 && response.statusCode < 500) {
          resolve();
          return;
        }
        retry();
      });
      request.on("error", retry);
      request.setTimeout(1000, () => {
        request.destroy();
        retry();
      });
    };
    tick();
  });
}

function fileUrlToPath(value) {
  const url = new URL(value);
  return decodeURIComponent(url.pathname);
}

function cssEscape(value) {
  return String(value).replace(/["\\]/g, "\\$&");
}

async function signUp(context, baseUrl, actorId) {
  const response = await context.request.fetch(`${baseUrl}/api/auth`, {
    method: "POST",
    data: {
      action: "auth:signIn",
      args: {
        provider: "password",
        params: {
          email: `${actorId}@example.com`,
          username: actorId,
          name: actorId,
          password: TEST_PASSWORD,
          flow: "signUp",
        },
      },
    },
  });
  assert(response.ok(), `测试账号注册失败: ${response.status()} ${await response.text()}`);
}

async function openDefaultLocalWorkspace(page, baseUrl) {
  await page.goto(baseUrl, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
  const createButton = page.locator('[data-testid="mnote-create-default-local-workspace"]').first();
  if (await createButton.isVisible({ timeout: 3000 }).catch(() => false)) {
    await createButton.click({ timeout: UI_TIMEOUT_MS });
    await page.waitForURL((url) => url.searchParams.get("sourceKind") === "local_folder", {
      timeout: UI_TIMEOUT_MS,
    });
  }
  const url = new URL(page.url());
  const rootUri = url.searchParams.get("rootUri")
    || await page.evaluate(() => document.body.getAttribute("data-mnote-root-uri") || "");
  assert(rootUri, "应进入 local_folder workspace");
  return {
    rootUri,
    workspaceId: url.searchParams.get("workspaceId") || "",
  };
}

async function setFileTreeExpanded(page, relativePath, expanded) {
  const rowSelector = `#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="${relativePath}"]`;
  await page.locator(rowSelector).waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  const row = page.locator(rowSelector).first();
  const current = await row.getAttribute("aria-expanded");
  if ((current === "true") !== expanded) {
    await row.locator('[data-rust-action="toggle"]').click({ timeout: UI_TIMEOUT_MS });
  }
  await page.waitForFunction(
    ({ selector, expected }) => {
      const row = document.querySelector(selector);
      return row && row.getAttribute("aria-expanded") === String(expected);
    },
    { selector: rowSelector, expected: expanded },
    { timeout: UI_TIMEOUT_MS },
  );
}

async function setPageRowExpanded(page, nodeId, expanded) {
  const selector = `#sidebar-tree-root .tree-row[data-shell-mode="page"][data-node-id="${cssEscape(nodeId)}"]`;
  const row = page.locator(selector).first();
  await row.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  const current = await row.getAttribute("aria-expanded");
  if ((current === "true") !== expanded) {
    await row.locator('[data-rust-action="toggle"]').click({ timeout: UI_TIMEOUT_MS });
  }
  await page.waitForFunction(
    ({ targetNodeId, expected }) => {
      const row = document.querySelector(`#sidebar-tree-root .tree-row[data-shell-mode="page"][data-node-id="${CSS.escape(targetNodeId)}"]`);
      return row && row.getAttribute("aria-expanded") === String(expected);
    },
    { targetNodeId: nodeId, expected: expanded },
    { timeout: UI_TIMEOUT_MS },
  );
}

async function visibleTreeState(page) {
  return page.evaluate(() => ({
    href: location.href,
    fileTree: Array.from(document.querySelectorAll("#sidebar-file-tree-root .tree-row[data-shell-mode='filetree']")).map((row) => ({
      path: row.getAttribute("data-local-relative-path") || "",
      expanded: row.getAttribute("aria-expanded") || "",
      text: row.textContent || "",
    })).filter((row) => row.path),
    pageTree: Array.from(document.querySelectorAll("#sidebar-tree-root .tree-row[data-shell-mode='page']")).map((row) => ({
      nodeId: row.getAttribute("data-node-id") || "",
      expanded: row.getAttribute("aria-expanded") || "",
      text: row.textContent || "",
    })),
    markers: {
      saved: document.documentElement.getAttribute("data-mnote-sidebar-tree-view-state-saved") || "",
      pageApplied: document.documentElement.getAttribute("data-mnote-page-tree-view-state-applied") || "",
      loadError: document.documentElement.getAttribute("data-mnote-sidebar-tree-view-state-load-error") || "",
      saveError: document.documentElement.getAttribute("data-mnote-sidebar-tree-view-state-save-error") || "",
    },
  }));
}

async function main() {
  fs.mkdirSync(RESULT_DIR, { recursive: true });
  const port = await pickPort();
  const baseUrl = `http://127.0.0.1:${port}`;
  const dataRoot = fs.mkdtempSync(path.join(os.tmpdir(), `${TASK}-`));
  const dbPath = path.join(dataRoot, "control-plane.sqlite3");
  const actorId = `${TASK}-${process.pid}-${Date.now()}`;
  const server = spawn("cargo", ["run", "-p", "mnote-web", "--bin", "mnote-web"], {
    cwd: path.join(__dirname, "..", "rust"),
    env: {
      ...process.env,
      MNOTE_WEB_BIND: `127.0.0.1:${port}`,
      MNOTE_WEB_PUBLIC_BIND: `127.0.0.1:${port}`,
      MNOTE_WEB_ENABLE_LEGACY_NEXT_COMPAT: "0",
      MNOTE_CONTROL_PLANE_DB_PATH: dbPath,
      MNOTE_LOCAL_WORKSPACE_BASE_DIR: dataRoot,
    },
    stdio: ["ignore", "pipe", "pipe"],
  });
  let stderr = "";
  server.stderr.on("data", (chunk) => {
    stderr += chunk.toString();
  });

  const executablePath = resolveChromiumExecutablePath();
  const browser = await chromium.launch({
    headless: true,
    ...(executablePath ? { executablePath } : {}),
  });
  const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
  const page = await context.newPage();
  const diagnostics = [];
  const viewStateRequests = [];
  const screenshots = [];
  const timeline = {};
  page.on("console", (message) => diagnostics.push(`console:${message.type()}:${message.text()}`));
  page.on("pageerror", (error) => diagnostics.push(`pageerror:${error.message}`));
  page.on("request", (request) => {
    if (request.url().includes("/api/tree/view-state")) {
      viewStateRequests.push({
        method: request.method(),
        url: request.url(),
        at: Date.now(),
        postData: request.postData() || "",
      });
    }
  });
  page.on("response", async (response) => {
    if (!response.url().includes("/api/tree/view-state")) return;
    const matching = viewStateRequests.findLast((entry) => entry.url === response.url() && !entry.status);
    if (!matching) return;
    matching.status = response.status();
    matching.doneAt = Date.now();
    matching.durationMs = matching.doneAt - matching.at;
    matching.body = await response.text().catch(() => "");
  });

  try {
    await waitForHttpOk(`${baseUrl}/health`, 60_000);
    await signUp(context, baseUrl, actorId);
    const { rootUri, workspaceId } = await openDefaultLocalWorkspace(page, baseUrl);
    const rootPath = fileUrlToPath(rootUri);
    fs.mkdirSync(path.join(rootPath, "design", "05-editor-mainline", "process"), { recursive: true });
    fs.mkdirSync(path.join(rootPath, "design", "05-editor-mainline", "reference"), { recursive: true });
    fs.writeFileSync(path.join(rootPath, "Home.md"), "# Home\n", "utf8");
    fs.writeFileSync(path.join(rootPath, "design", "05-editor-mainline", "process", "Target.md"), "# Target\n", "utf8");
    fs.writeFileSync(path.join(rootPath, "design", "05-editor-mainline", "reference", "Ref.md"), "# Ref\n", "utf8");

    const workspaceUrl = new URL(baseUrl);
    if (workspaceId) workspaceUrl.searchParams.set("workspaceId", workspaceId);
    workspaceUrl.searchParams.set("sourceKind", "local_folder");
    workspaceUrl.searchParams.set("rootUri", rootUri);
    workspaceUrl.searchParams.set("treeView", "filetree");
    await page.goto(workspaceUrl.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await page.locator('[data-mnote-sidebar-tree-tab="filetree"]').click({ timeout: UI_TIMEOUT_MS });
    const designRow = page.locator('#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="design"]').first();
    await designRow.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await designRow.click({ button: "right", timeout: UI_TIMEOUT_MS });
    await page.getByText("加入/取消星标置顶").click({ timeout: UI_TIMEOUT_MS });
    await page.locator('.wolai-starred-section [data-mnote-shortcut-kind="folder"][data-mnote-shortcut-relative-path="design"]').first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });

    await page.goto(baseUrl, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    const designShortcut = page.locator('.wolai-starred-section [data-mnote-shortcut-kind="folder"][data-mnote-shortcut-relative-path="design"]').first();
    timeline.starClickAt = Date.now();
    await designShortcut.click({ timeout: UI_TIMEOUT_MS });
    await page.locator('#sidebar-file-tree-root[data-mnote-filetree-scope="design"] .tree-row[data-local-relative-path="design/05-editor-mainline"]').waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    await page.waitForFunction(() => {
      const root = document.querySelector("#sidebar-tree-root");
      return root instanceof HTMLElement && /05-editor-mainline|Target|Ref/.test(root.innerText || "");
    }, { timeout: UI_TIMEOUT_MS });
    screenshots.push(path.join(RESULT_DIR, "01-after-starred-design.png"));
    await page.screenshot({ path: screenshots.at(-1), fullPage: true });

    const fileSavePromise = page.waitForResponse((response) => {
      return response.url().includes("/api/tree/view-state")
        && response.request().method() === "PUT"
        && /"treeKind":"filetree"/.test(response.request().postData() || "");
    }, { timeout: UI_TIMEOUT_MS }).catch((error) => error);
    await setFileTreeExpanded(page, "design/05-editor-mainline", true);
    await setFileTreeExpanded(page, "design/05-editor-mainline/process", true);
    const fileSaveResult = await fileSavePromise;
    if (fileSaveResult instanceof Error) {
      throw new Error(`未观察到 FileTree view-state PUT: ${fileSaveResult.message}; state=${JSON.stringify(await visibleTreeState(page))}; requests=${JSON.stringify(viewStateRequests)}`);
    }
    assert(fileSaveResult.ok(), `FileTree view-state PUT 失败: ${fileSaveResult.status()}`);
    timeline.fileStateSavedAt = Date.now();

    await page.locator('[data-mnote-sidebar-tree-tab="page"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-mnote-sidebar-tree-panel="page"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const pageRows = await page.evaluate(() => Array.from(document.querySelectorAll("#sidebar-tree-root .tree-row[data-shell-mode='page'][aria-expanded]")).filter((row) => {
      const rect = row.getBoundingClientRect();
      const style = window.getComputedStyle(row);
      return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none";
    }).map((row) => ({
      nodeId: row.getAttribute("data-node-id") || "",
      parentId: row.getAttribute("data-parent-id") || "",
      expanded: row.getAttribute("aria-expanded") || "",
      text: row.textContent || "",
    })).filter((row) => row.nodeId));
    const siblingPair = pageRows.flatMap((row, index) => {
      return pageRows.slice(index + 1).filter((candidate) => candidate.parentId === row.parentId).map((candidate) => [row, candidate]);
    })[0];
    assert(siblingPair, `PageTree 应至少有两个同级可展开节点: ${JSON.stringify(pageRows)}`);
    const pageCollapsed = siblingPair[0].nodeId;
    const pageExpanded = siblingPair[1].nodeId;
    const pageSavePromise = page.waitForResponse((response) => {
      return response.url().includes("/api/tree/view-state")
        && response.request().method() === "PUT"
        && /"treeKind":"pagetree"/.test(response.request().postData() || "");
    }, { timeout: UI_TIMEOUT_MS }).catch((error) => error);
    await setPageRowExpanded(page, pageExpanded, false);
    await setPageRowExpanded(page, pageCollapsed, false);
    await setPageRowExpanded(page, pageExpanded, true);
    const pageSaveResult = await pageSavePromise;
    if (pageSaveResult instanceof Error) {
      throw new Error(`未观察到 PageTree view-state PUT: ${pageSaveResult.message}; state=${JSON.stringify(await visibleTreeState(page))}; requests=${JSON.stringify(viewStateRequests)}`);
    }
    assert(pageSaveResult.ok(), `PageTree view-state PUT 失败: ${pageSaveResult.status()}`);
    timeline.pageStateSavedAt = Date.now();
    screenshots.push(path.join(RESULT_DIR, "02-after-state-edits.png"));
    await page.screenshot({ path: screenshots.at(-1), fullPage: true });

    await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => document.documentElement.getAttribute("data-mnote-sidebar-tree-view-state-saved") || document.querySelector("#sidebar-file-tree-root"), { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-mnote-sidebar-tree-tab="filetree"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('#sidebar-file-tree-root[data-mnote-filetree-scope="design"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => {
      const row = document.querySelector('#sidebar-file-tree-root .tree-row[data-local-relative-path="design/05-editor-mainline/process"]');
      return row && row.getAttribute("aria-expanded") === "true";
    }, { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-mnote-sidebar-tree-tab="page"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      ({ pageCollapsed, pageExpanded }) => {
        const collapsed = document.querySelector(`#sidebar-tree-root .tree-row[data-shell-mode="page"][data-node-id="${CSS.escape(pageCollapsed)}"]`);
        const expanded = document.querySelector(`#sidebar-tree-root .tree-row[data-shell-mode="page"][data-node-id="${CSS.escape(pageExpanded)}"]`);
        return collapsed && expanded
          && collapsed.getAttribute("aria-expanded") === "false"
          && expanded.getAttribute("aria-expanded") === "true";
      },
      { pageCollapsed, pageExpanded },
      { timeout: UI_TIMEOUT_MS },
    );
    timeline.reloadedStateRestoredAt = Date.now();

    const targetRow = page.locator('#sidebar-file-tree-root .tree-row[data-local-relative-path="design/05-editor-mainline/process/Target.md"]').first();
    await page.locator('[data-mnote-sidebar-tree-tab="filetree"]').click({ timeout: UI_TIMEOUT_MS });
    await targetRow.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await targetRow.locator(".tree-link").click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      () => location.pathname.startsWith("/documents/")
        && decodeURIComponent(location.pathname).includes("Target.md")
        && new URLSearchParams(location.search).get("fileTreeScope") === "design",
      { timeout: UI_TIMEOUT_MS },
    );
    await page.locator(".document-pane[data-pane-role='primary'] .editor-surface .ProseMirror").first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    await page.goBack({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }).catch(() => page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }));
    await page.waitForFunction(() => {
      const row = document.querySelector('#sidebar-file-tree-root .tree-row[data-local-relative-path="design/05-editor-mainline/process"]');
      return row && row.getAttribute("aria-expanded") === "true";
    }, { timeout: UI_TIMEOUT_MS });
    timeline.afterNavigationRestoredAt = Date.now();
    screenshots.push(path.join(RESULT_DIR, "03-after-reload-and-navigation.png"));
    await page.screenshot({ path: screenshots.at(-1), fullPage: true });

    const finalState = await visibleTreeState(page);
    assert.equal(
      finalState.fileTree.find((row) => row.path === "design/05-editor-mainline")?.expanded,
      "true",
      `FileTree 父节点应恢复展开: ${JSON.stringify(finalState.fileTree)}`,
    );
    assert.equal(
      finalState.fileTree.find((row) => row.path === "design/05-editor-mainline/process")?.expanded,
      "true",
      `FileTree process 节点应恢复展开: ${JSON.stringify(finalState.fileTree)}`,
    );
    assert.equal(
      finalState.pageTree.find((row) => row.nodeId === pageCollapsed)?.expanded,
      "false",
      `PageTree 折叠态应恢复: ${JSON.stringify(finalState.pageTree)}`,
    );
    assert.equal(
      finalState.pageTree.find((row) => row.nodeId === pageExpanded)?.expanded,
      "true",
      `PageTree 展开态应恢复: ${JSON.stringify(finalState.pageTree)}`,
    );
    assert(viewStateRequests.some((entry) => entry.method === "GET" && entry.status === 200), "应记录 view-state GET");
    assert(viewStateRequests.some((entry) => entry.method === "PUT" && entry.status === 200 && /filetree/.test(entry.postData)), "应记录 FileTree view-state PUT");
    assert(viewStateRequests.some((entry) => entry.method === "PUT" && entry.status === 200 && /pagetree/.test(entry.postData)), "应记录 PageTree view-state PUT");

    const result = {
      ok: true,
      task: TASK,
      baseUrl,
      rootUri,
      workspaceId,
      pageCollapsed,
      pageExpanded,
      timeline,
      viewStateRequests,
      finalState,
      screenshots,
    };
    fs.writeFileSync(path.join(RESULT_DIR, "result.json"), JSON.stringify(result, null, 2));
    console.log(JSON.stringify(result, null, 2));
  } catch (error) {
    const failureState = await visibleTreeState(page).catch(() => null);
    const failureScreenshot = path.join(RESULT_DIR, "99-failure.png");
    await page.screenshot({ path: failureScreenshot, fullPage: true }).catch(() => {});
    const result = {
      ok: false,
      task: TASK,
      error: error && error.stack ? error.stack : String(error),
      diagnostics: diagnostics.slice(-30),
      viewStateRequests,
      failureState,
      screenshot: failureScreenshot,
      stderr: stderr.slice(-8000),
    };
    fs.writeFileSync(path.join(RESULT_DIR, "failure.json"), JSON.stringify(result, null, 2));
    console.error(JSON.stringify(result, null, 2));
    process.exitCode = 1;
  } finally {
    await browser.close().catch(() => {});
    server.kill("SIGTERM");
  }
}

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