#!/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 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 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="wolai-page-settings-popover"]');
      return {
        backlinksHtml: bl ? bl.innerHTML : '(missing)',
        tagsHtml: tg ? tg.innerHTML : '(missing)',
        statusText: st ? st.textContent : '(missing)',
        popoverExists: Boolean(popover),
        popoverHidden: popover ? popover.hidden : null,
        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 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(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,
    });

    // 拦截 API 请求与页面错误做诊断
    var diagApiResponses = {};
    page.on('response', function onDiag(resp) {
      var url = resp.url();
      if (url.includes('/api/search/local-index/backlinks') || url.includes('/api/search/local-index/tags')) {
        resp.json().then(function(body) { diagApiResponses[url] = body; }).catch(function() {});
      }
    });
    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()]); }
    });

    await page.locator('[data-testid="wolai-page-settings-trigger"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-settings-tab="index"]').click({ timeout: UI_TIMEOUT_MS });

    // 等待本地索引面板渲染；超时时捕获 DOM 诊断再抛
    try {
      await page.waitForFunction(() => {
        var bl = document.querySelector('[data-testid="wolai-page-settings-local-index-backlinks"]');
        var tg = document.querySelector('[data-testid="wolai-page-settings-local-index-tags"]');
        return Boolean(
          bl && bl.textContent && bl.textContent.includes("README.md")
          && bl.textContent.includes("[Target](docs/search-target.md)")
          && tg && tg.textContent && tg.textContent.includes("#alpha"),
        );
      }, null, { timeout: UI_TIMEOUT_MS });
    } catch (waitError) {
      debug.diagApiResponses = diagApiResponses;
      debug.failedPanelState = await capturePanelDiagnostics(page);
      throw waitError;
    }

    debug.localIndexPanel = 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"]');
      return {
        backlinks: bl ? bl.innerHTML : '(missing)',
        tags: tg ? tg.innerHTML : '(missing)',
        status: st ? st.textContent : '(missing)',
      };
    });
    debug.diagApiResponses = diagApiResponses;

    fs.renameSync(path.join(root, firstRelativePath), path.join(root, renamedRelativePath));
    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;
});
