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

const assert = require("node:assert");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { chromium } = require("playwright");
const {
  BASE_URL,
  UI_TIMEOUT_MS,
} = require("./tree-shell-smoke-helpers");

const TASK = "task529-local-search-result-open-locator-smoke";
const OUT_DIR = path.join(process.cwd(), "tmp", TASK);
const RESULT_PATH = path.join(OUT_DIR, "result.json");
const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
  || ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium", "/usr/bin/chromium"]
    .find((candidate) => fs.existsSync(candidate));

function fileUrl(localPath) {
  return `file://${localPath}`;
}

function localMdDocumentId(relativePath) {
  return `local-md:${relativePath.replaceAll("/", "~2F")}`;
}

function documentUrl(root, relativePath) {
  const url = new URL(`${BASE_URL}/documents/${encodeURIComponent(localMdDocumentId(relativePath))}`);
  url.searchParams.set("sourceKind", "local_folder");
  url.searchParams.set("rootUri", fileUrl(root));
  url.searchParams.set("treeView", "filetree");
  return url.toString();
}

async function saveScreenshot(page, name) {
  const target = path.join(OUT_DIR, `${name}.png`);
  await page.screenshot({ path: target, fullPage: false });
  return target;
}

async function loginTestAccount(page) {
  await page.goto(`${BASE_URL}/auth`, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
  if (page.url().includes("/auth")) {
    const quickLogin = page.locator('[data-auth-test-login]').first();
    await quickLogin.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await quickLogin.click({ timeout: UI_TIMEOUT_MS });
    await page.waitForURL((url) => !url.toString().includes("/auth"), {
      waitUntil: "commit",
      timeout: UI_TIMEOUT_MS,
    });
  }
  return await page.evaluate(async () => {
    const response = await fetch("/api/auth/whoami", { headers: { accept: "application/json" } });
    return await response.json();
  });
}

async function main() {
  fs.mkdirSync(OUT_DIR, { recursive: true });
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task529-search-"));
  const rootUri = fileUrl(root);
  const query = "三甲基硅酯";
  const currentPath = "Current.md";
  const targetPath = "docs/Silicon.md";
  const debug = { root, rootUri, query, baseUrl: BASE_URL };

  const browser = await chromium.launch({
    headless: process.env.HEADFUL !== "1",
    ...(CHROMIUM_EXECUTABLE_PATH ? { executablePath: CHROMIUM_EXECUTABLE_PATH } : {}),
  });
  const context = await browser.newContext({
    viewport: { width: 1440, height: 960 },
    locale: "zh-CN",
  });
  const page = await context.newPage();

  try {
    const viewer = await loginTestAccount(page);
    const actorId = viewer.userId || "mnote-e2e";
    const workspaceId = `local-ws:${actorId}:task529`;
    debug.viewer = viewer;
    debug.workspaceId = workspaceId;

    fs.mkdirSync(path.join(root, ".mnote"), { recursive: true });
    fs.mkdirSync(path.join(root, "docs"), { recursive: true });
    fs.writeFileSync(
      path.join(root, ".mnote", "workspace.json"),
      `${JSON.stringify({
        workspaceId,
        ownerId: actorId,
        createdAt: new Date().toISOString(),
        capabilities: ["local_files", "search"],
      }, null, 2)}\n`,
      "utf8",
    );
    fs.writeFileSync(path.join(root, currentPath), "# Current\n\n从这个页面打开搜索结果。\n", "utf8");
    const filler = Array.from({ length: 42 }, (_, index) => `普通段落 ${index + 1}。`).join("\n\n");
    fs.writeFileSync(
      path.join(root, targetPath),
      `# Silicon\n\n${filler}\n\n命中段落：羧酸可以转化成${query}，本行用于测试搜索定位。\n\n尾部段落。\n`,
      "utf8",
    );

    await page.goto(documentUrl(root, currentPath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]').first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });

    const refresh = await page.evaluate(async ({ workspaceId, rootUri }) => {
      const response = await fetch("/api/search/local-index/settings", {
        method: "PUT",
        headers: { "content-type": "application/json", accept: "application/json" },
        body: JSON.stringify({
          workspaceId,
          rootUri,
          includePaths: ["."],
          scheduleMode: "manual",
          scheduleTime: "02:00",
          runOnChange: false,
        }),
      });
      return { status: response.status, payload: await response.json().catch(() => null) };
    }, { workspaceId, rootUri });
    assert.equal(refresh.status, 200, `刷新本地索引应成功: ${JSON.stringify(refresh)}`);
    debug.refresh = refresh.payload;

    await page.locator('[data-mnote-action="open-search-modal"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="wolai-search-input"]').fill(query, { timeout: UI_TIMEOUT_MS });
    await page.waitForFunction((expected) => {
      return Array.from(document.querySelectorAll('[data-testid="wolai-search-result-row"]'))
        .some((row) => (row.textContent || "").includes(expected));
    }, query, { timeout: UI_TIMEOUT_MS });
    debug.searchScreenshot = await saveScreenshot(page, "search-results");

    await page.locator('[data-testid="wolai-search-result-row"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction((expected) => {
      const activeTab = document.querySelector('.mnote-main-tab[aria-selected="true"][data-mnote-tab-kind="markdown"]');
      const highlighted = document.querySelector('[data-mnote-resource-tab-panel][data-pane-role="primary"] [data-mnote-evidence-text-highlight="true"]');
      const visibleHit = Array.from(document.querySelectorAll('[data-mnote-resource-tab-panel][data-pane-role="primary"]:not([hidden]) .ProseMirror *'))
        .find((node) => node instanceof HTMLElement && (node.textContent || "").includes(expected));
      return Boolean(activeTab && (
        highlighted && (highlighted.textContent || "").includes(expected)
        || visibleHit && visibleHit.getBoundingClientRect().top > 80 && visibleHit.getBoundingClientRect().bottom < window.innerHeight
      ));
    }, query, { timeout: UI_TIMEOUT_MS });
    debug.openScreenshot = await saveScreenshot(page, "opened-resource-tab");

    const state = await page.evaluate((expectedCurrentPath) => {
      const url = new URL(window.location.href);
      const activeTab = document.querySelector('.mnote-main-tab[aria-selected="true"][data-mnote-tab-kind="markdown"]');
      const highlighted = document.querySelector('[data-mnote-resource-tab-panel][data-pane-role="primary"] [data-mnote-evidence-text-highlight="true"]');
      const visibleHit = Array.from(document.querySelectorAll('[data-mnote-resource-tab-panel][data-pane-role="primary"]:not([hidden]) .ProseMirror *'))
        .find((node) => node instanceof HTMLElement && (node.textContent || "").includes("三甲基硅酯"));
      const target = highlighted instanceof HTMLElement ? highlighted : visibleHit;
      const rect = target instanceof HTMLElement ? target.getBoundingClientRect() : null;
      return {
        pathname: url.pathname,
        stayedOnCurrentDocument: url.pathname.includes(encodeURIComponent(`local-md:${expectedCurrentPath}`)),
        resourceTab: url.searchParams.get("resourceTab") || "",
        activeTabTitle: activeTab ? activeTab.textContent.trim() : "",
        highlighted: Boolean(highlighted),
        highlightedText: target ? target.textContent.trim() : "",
        highlightedRect: rect ? { top: rect.top, bottom: rect.bottom, height: rect.height } : null,
      };
    }, currentPath);
    debug.state = state;
    assert.equal(state.stayedOnCurrentDocument, true, `点击搜索结果不应整页跳走: ${JSON.stringify(state)}`);
    assert(state.resourceTab.includes(targetPath), `URL 应记录当前资源标签: ${JSON.stringify(state)}`);
    assert(state.highlightedText.includes(query), `应高亮正文命中块: ${JSON.stringify(state)}`);
    assert(
      state.highlightedRect && state.highlightedRect.top > 80 && state.highlightedRect.bottom < 900,
      `命中块应滚动到可视区域: ${JSON.stringify(state)}`,
    );

    fs.writeFileSync(RESULT_PATH, `${JSON.stringify(debug, null, 2)}\n`, "utf8");
  } catch (error) {
    debug.error = error && error.stack || String(error);
    try {
      debug.failureScreenshot = await saveScreenshot(page, "failure");
    } catch (_) {}
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify(debug, null, 2)}\n`, "utf8");
    throw error;
  } finally {
    await browser.close().catch(() => undefined);
    fs.rmSync(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
  }
}

main().catch((error) => {
  console.error(error && error.stack || error);
  process.exit(1);
});
