#!/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 = (process.env.MNOTE_WEB_SMOKE_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);
const OUTPUT_DIR = path.join(process.cwd(), "tmp", "task452-local-search-index-browser-smoke");
const RESULT_PATH = path.join(OUTPUT_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));
  return url.toString();
}

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

function writeWorkspaceManifest(root, ownerId) {
  const metadataDir = path.join(root, ".mnote");
  fs.mkdirSync(metadataDir, { recursive: true });
  fs.writeFileSync(
    path.join(metadataDir, "workspace.json"),
    `${JSON.stringify({
      workspaceId: `local-ws:${ownerId}:task452`,
      ownerId,
      createdAt: new Date().toISOString(),
      capabilities: ["local_files", "search"],
    }, null, 2)}\n`,
    "utf8",
  );
}

async function browserSearch(page, root, query) {
  return page.evaluate(async ({ rootUri, queryText }) => {
    const response = await fetch("/api/search/documents", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        workspaceId: "local-ws:user_real:task452",
        sourceKind: "local_folder",
        rootUri,
        query: queryText,
        limit: 10,
      }),
    });
    const payload = await response.json();
    return {
      status: response.status,
      payload,
    };
  }, { rootUri: fileUrl(root), queryText: query });
}

async function browserRefreshLocalIndex(page, root) {
  return page.evaluate(async ({ rootUri }) => {
    const response = await fetch("/api/search/local-index/refresh", {
      method: "POST",
      headers: { "content-type": "application/json", accept: "application/json" },
      body: JSON.stringify({
        workspaceId: "local-ws:user_real:task452",
        rootUri,
      }),
    });
    const payload = await response.json().catch(() => null);
    return {
      status: response.status,
      payload,
    };
  }, { rootUri: fileUrl(root) });
}

async function browserUpdateLocalIndexSettings(page, root) {
  return page.evaluate(async ({ rootUri }) => {
    const response = await fetch("/api/search/local-index/settings", {
      method: "PUT",
      headers: { "content-type": "application/json", accept: "application/json" },
      body: JSON.stringify({
        workspaceId: "local-ws:user_real:task452",
        rootUri,
        includePaths: ["."],
        scheduleMode: "manual",
        scheduleTime: "02:00",
        runOnChange: false,
      }),
    });
    const payload = await response.json().catch(() => null);
    return {
      status: response.status,
      payload,
    };
  }, { rootUri: fileUrl(root) });
}

async function browserFetchLocalIndexBacklinksAndTags(page, root, documentId) {
  return page.evaluate(async ({ rootUri, documentIdValue }) => {
    const backlinksParams = new URLSearchParams({
      workspaceId: "local-ws:user_real:task452",
      rootUri,
      documentId: documentIdValue,
    });
    const tagsParams = new URLSearchParams({
      workspaceId: "local-ws:user_real:task452",
      rootUri,
    });
    const backlinksResponse = await fetch(`/api/search/local-index/backlinks?${backlinksParams.toString()}`, {
      headers: { accept: "application/json" },
    });
    const tagsResponse = await fetch(`/api/search/local-index/tags?${tagsParams.toString()}`, {
      headers: { accept: "application/json" },
    });
    return {
      backlinks: {
        status: backlinksResponse.status,
        payload: await backlinksResponse.json().catch(() => null),
      },
      tags: {
        status: tagsResponse.status,
        payload: await tagsResponse.json().catch(() => null),
      },
    };
  }, { rootUri: fileUrl(root), documentIdValue: documentId });
}

async function capturePanelDiagnostics(page) {
  try {
    return await page.evaluate(function() {
      var bl = document.querySelector('[data-testid="wolai-page-settings-local-index-backlinks"]');
      var tg = document.querySelector('[data-testid="wolai-page-settings-local-index-tags"]');
      var st = document.querySelector('[data-testid="wolai-page-settings-local-index-status"]');
      var popover = document.querySelector('[data-testid="mnote-local-index-settings-popover"]');
      var ranges = document.querySelector('[data-testid="wolai-page-settings-local-index-ranges"]');
      var pageSettingsIndexTab = document.querySelector('[data-page-settings-tab="index"]');
      return {
        backlinksHtml: bl ? bl.innerHTML : '(missing)',
        tagsHtml: tg ? tg.innerHTML : '(missing)',
        statusText: st ? st.textContent : '(missing)',
        popoverExists: Boolean(popover),
        popoverHidden: popover ? popover.hidden : null,
        rangeInputs: ranges ? ranges.querySelectorAll('[data-local-index-range-input]').length : 0,
        hasPageSettingsIndexTab: Boolean(pageSettingsIndexTab),
        locationHref: window.location.href,
      };
    });
  } catch (_) {
    return { error: 'evaluate failed' };
  }
}

async function run() {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-local-search-smoke-"));
  const debug = { root, baseUrl: BASE_URL };
  writeWorkspaceManifest(root, "user_real");
  fs.mkdirSync(path.join(root, "docs"), { recursive: true });
  const token = `LOCAL-SEARCH-${Date.now()}`;
  const firstRelativePath = "docs/search-target.md";
  const renamedRelativePath = "docs/search-renamed.md";
  fs.writeFileSync(
    path.join(root, "README.md"),
    `---\ntitle: Search Smoke\ntags: [alpha]\n---\n# Search Smoke\n打开搜索 smoke。\n[Target](docs/search-target.md)\n`,
    "utf8",
  );

  const browser = await chromium.launch({
    headless: true,
    ...(CHROMIUM_EXECUTABLE_PATH ? { executablePath: CHROMIUM_EXECUTABLE_PATH } : {}),
  });
  const context = await browser.newContext({
    viewport: { width: 1280, height: 860 },
    extraHTTPHeaders: {
      "x-mnote-actor-id": "user_real",
      "x-mnote-actor-type": "user",
    },
  });
  const page = await context.newPage();

  try {
    await page.goto(documentUrl(root, "README.md"), {
      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,
    });

    fs.writeFileSync(
      path.join(root, firstRelativePath),
      `---\ntitle: Search Target\ntags: [alpha, beta]\n---\n# Search Target\n${token}\n`,
      "utf8",
    );

    const settingsBeforeSearch = await browserUpdateLocalIndexSettings(page, root);
    assert.equal(settingsBeforeSearch.status, 200, `更新本地索引设置应成功: ${JSON.stringify(settingsBeforeSearch)}`);
    debug.settingsBeforeSearch = settingsBeforeSearch.payload;
    const refreshedBeforeSearch = await browserRefreshLocalIndex(page, root);
    assert.equal(refreshedBeforeSearch.status, 200, `刷新本地索引应成功: ${JSON.stringify(refreshedBeforeSearch)}`);
    debug.refreshedBeforeSearch = refreshedBeforeSearch.payload;
    const first = await browserSearch(page, root, token);
    assert.equal(first.status, 200, `初次搜索应成功: ${JSON.stringify(first)}`);
    debug.first = first.payload;
    const firstResults = Array.isArray(first.payload.results) ? first.payload.results : [];
    assert(
      firstResults.some((item) => item.path === firstRelativePath && item.documentId === localMdDocumentId(firstRelativePath)),
      `新建页面应立即可搜索: ${JSON.stringify(firstResults)}`,
    );

    await page.goto(navigationUrl(root), {
      waitUntil: "domcontentloaded",
      timeout: UI_TIMEOUT_MS,
    });
    debug.navigationIndexSettings = await page.evaluate(function() {
      var indexToggle = document.querySelector('[data-testid="mnote-local-index-settings-toggle"]');
      var ragToggle = document.querySelector('[data-testid="mnote-knowledge-rag-settings-toggle"]');
      var pageSettingsIndexTab = document.querySelector('[data-page-settings-tab="index"]');
      return {
        path: window.location.pathname,
        hasLocalIndexToggle: Boolean(indexToggle),
        hasKnowledgeRagToggle: Boolean(ragToggle),
        hasPageSettingsIndexTab: Boolean(pageSettingsIndexTab),
      };
    });
    assert.equal(debug.navigationIndexSettings.hasLocalIndexToggle, false, `导航页不应恢复旧本地索引设置入口: ${JSON.stringify(debug.navigationIndexSettings)}`);
    assert.equal(debug.navigationIndexSettings.hasKnowledgeRagToggle, true, `导航页应保留资料库问答入口: ${JSON.stringify(debug.navigationIndexSettings)}`);
    assert.equal(debug.navigationIndexSettings.hasPageSettingsIndexTab, false, `索引设置不应留在页面设置页签: ${JSON.stringify(debug.navigationIndexSettings)}`);

    await page.goto(documentUrl(root, firstRelativePath), {
      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,
    });

    // 拦截页面错误做诊断；backlink/tag 当前不再由索引面板渲染，下面走 API 直验。
    var diagApiResponses = {};
    page.on('pageerror', function onPageError(err) { diagApiResponses._pageError = String(err); });
    page.on('console', function onConsole(msg) {
      if (msg.type() === 'error') { diagApiResponses._consoleErrors = (diagApiResponses._consoleErrors || []).concat([msg.text()]); }
    });

    debug.localIndexPanel = await page.evaluate(function() {
      var indexToggle = document.querySelector('[data-testid="mnote-local-index-settings-toggle"]');
      var ragToggle = document.querySelector('[data-testid="mnote-knowledge-rag-settings-toggle"]');
      var pageSettingsIndexTab = document.querySelector('[data-page-settings-tab="index"]');
      return {
        hasLocalIndexToggle: Boolean(indexToggle),
        hasKnowledgeRagToggle: Boolean(ragToggle),
        hasPageSettingsIndexTab: Boolean(pageSettingsIndexTab),
        hasLegacyBacklinksDom: Boolean(document.querySelector('[data-testid="wolai-page-settings-local-index-backlinks"]')),
        hasLegacyTagsDom: Boolean(document.querySelector('[data-testid="wolai-page-settings-local-index-tags"]')),
      };
    });
    debug.diagApiResponses = diagApiResponses;
    assert.equal(debug.localIndexPanel.hasLocalIndexToggle, false, `文档页不应恢复旧本地索引设置入口: ${JSON.stringify(debug.localIndexPanel)}`);
    assert.equal(debug.localIndexPanel.hasKnowledgeRagToggle, true, `文档页应保留资料库问答入口: ${JSON.stringify(debug.localIndexPanel)}`);
    assert.equal(debug.localIndexPanel.hasPageSettingsIndexTab, false, `文档页索引设置不应回落到页面设置页签: ${JSON.stringify(debug.localIndexPanel)}`);
    assert.equal(debug.localIndexPanel.hasLegacyBacklinksDom, false, `独立索引面板不应恢复旧 backlink DOM: ${JSON.stringify(debug.localIndexPanel)}`);
    assert.equal(debug.localIndexPanel.hasLegacyTagsDom, false, `独立索引面板不应恢复旧 tags DOM: ${JSON.stringify(debug.localIndexPanel)}`);

    const backlinksAndTags = await browserFetchLocalIndexBacklinksAndTags(page, root, localMdDocumentId(firstRelativePath));
    assert.equal(backlinksAndTags.backlinks.status, 200, `反链 API 应继续可用: ${JSON.stringify(backlinksAndTags)}`);
    assert.equal(backlinksAndTags.tags.status, 200, `标签 API 应继续可用: ${JSON.stringify(backlinksAndTags)}`);
    debug.backlinksAndTags = backlinksAndTags;
    const backlinks = backlinksAndTags.backlinks.payload?.result?.backlinks || [];
    assert(
      backlinks.some((item) => item.documentId === localMdDocumentId("README.md")),
      `本地索引反链应能找到 README.md: ${JSON.stringify(backlinksAndTags.backlinks.payload)}`,
    );
    const tags = backlinksAndTags.tags.payload?.result?.tags || [];
    assert(
      tags.some((item) => item.tag === "alpha"),
      `本地索引标签 API 应能返回 alpha: ${JSON.stringify(backlinksAndTags.tags.payload)}`,
    );

    fs.renameSync(path.join(root, firstRelativePath), path.join(root, renamedRelativePath));
    const refreshedAfterRename = await browserRefreshLocalIndex(page, root);
    assert.equal(refreshedAfterRename.status, 200, `重命名后刷新本地索引应成功: ${JSON.stringify(refreshedAfterRename)}`);
    debug.refreshedAfterRename = refreshedAfterRename.payload;
    const second = await browserSearch(page, root, token);
    assert.equal(second.status, 200, `重命名后搜索应成功: ${JSON.stringify(second)}`);
    debug.second = second.payload;
    const secondResults = Array.isArray(second.payload.results) ? second.payload.results : [];
    assert(
      secondResults.some((item) => item.path === renamedRelativePath && item.documentId === localMdDocumentId(renamedRelativePath)),
      `重命名后搜索结果路径应更新: ${JSON.stringify(secondResults)}`,
    );
    assert(
      !secondResults.some((item) => item.path === firstRelativePath),
      `重命名后搜索结果不应继续返回旧路径: ${JSON.stringify(secondResults)}`,
    );

    const result = {
      ok: true,
      root,
      token,
      firstPath: firstRelativePath,
      renamedPath: renamedRelativePath,
      localIndexPanel: debug.localIndexPanel,
      indexExists: fs.existsSync(path.join(root, ".mnote", "index", "search-index.json")),
    };
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify(result, null, 2)}\n`, "utf8");
    console.log(`task452 local search index browser smoke passed: ${RESULT_PATH}`);
  } catch (error) {
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify({
      ok: false,
      error: String(error && error.stack || error),
      debug,
    }, null, 2)}\n`, "utf8");
    throw error;
  } finally {
    await browser.close().catch(() => {});
    fs.rmSync(root, { recursive: true, force: true });
  }
}

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