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

const assert = require("node:assert");
const fs = require("node:fs");
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 ROOT_URI = process.env.MNOTE_KNOWLEDGE_RAG_ROOT_URI || "file:///mnt/Data1T/Mnote_data/users/mnote-e2e/workspaces/my-space";
const WORKSPACE_ID = process.env.MNOTE_KNOWLEDGE_RAG_WORKSPACE_ID || "local-ws:mnote-e2e:my-space";
const QUERY = process.env.MNOTE_KNOWLEDGE_RAG_QUERY || "image copy 6.png";
const EXPECTED_RESOURCE = process.env.MNOTE_KNOWLEDGE_RAG_EXPECTED_RESOURCE || "新页面233155/image copy 6.png";
const OUTPUT_DIR = path.join(process.cwd(), "tmp", "task529-knowledge-rag-citation-resource-tab-smoke");
const RESULT_PATH = path.join(OUTPUT_DIR, "result.json");
const SCREENSHOT_PATH = path.join(OUTPUT_DIR, "citation-resource-tab.png");
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);
const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
  || ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium"]
    .find((candidate) => fs.existsSync(candidate));

async function assertKnowledgeRagDescriptor(requestContext) {
  const response = await requestContext.get(`${BASE_URL}/api/page-ai/agents/descriptors?profile=task529-knowledge-rag`);
  assert(response.ok(), `descriptor API 失败: ${response.status()} ${await response.text()}`);
  const payload = await response.json();
  const reasonix = (payload.descriptors || []).find((descriptor) => descriptor.agentId === "reasonix");
  assert(reasonix, "descriptor 缺少 Reasonix");
  assert.equal(reasonix.capabilityStates?.knowledge_rag?.enabled, true, "Reasonix descriptor 应声明 knowledge_rag enabled");
  assert((reasonix.capabilities || []).includes("knowledge_rag"), "Reasonix descriptor capabilities 应包含 knowledge_rag");
  const toolNames = new Set((reasonix.tools || []).map((tool) => tool.name));
  for (const toolName of ["mnote.knowledge_rag.status", "mnote.knowledge_rag.query", "mnote.knowledge_rag.open_reference"]) {
    assert(toolNames.has(toolName), `Reasonix descriptor 缺少 ${toolName}`);
  }
}

async function status(requestContext) {
  const params = new URLSearchParams({ rootUri: ROOT_URI, workspaceId: WORKSPACE_ID });
  const response = await requestContext.get(`${BASE_URL}/api/knowledge-rag/status?${params.toString()}`);
  assert(response.ok(), `knowledge-rag status 失败: ${response.status()} ${await response.text()}`);
  return await response.json();
}

async function ensureIndexed(requestContext) {
  const ingestResponse = await requestContext.post(`${BASE_URL}/api/knowledge-rag/ingest`, {
    data: {
      rootUri: ROOT_URI,
      workspaceId: WORKSPACE_ID,
      sources: [{ sourcePath: EXPECTED_RESOURCE }],
    },
  });
  assert(ingestResponse.ok(), `knowledge-rag ingest 失败: ${ingestResponse.status()} ${await ingestResponse.text()}`);
  const startedAt = Date.now();
  let lastEntry = null;
  while (Date.now() - startedAt < 90_000) {
    const payload = await status(requestContext);
    lastEntry = (payload.registry?.entries || []).find((entry) => entry.sourceRootRelativePath === EXPECTED_RESOURCE) || null;
    if (lastEntry?.indexedAtMs && lastEntry?.lightRagDocId && !lastEntry?.stale && !lastEntry?.deletedAtMs) return lastEntry;
    await new Promise((resolve) => setTimeout(resolve, 5_000));
  }
  throw new Error(`等待目标资料入库超时: ${JSON.stringify(lastEntry, null, 2)}`);
}

async function main() {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const browser = await chromium.launch({ headless: true, executablePath: CHROMIUM_EXECUTABLE_PATH });
  const context = await browser.newContext({ viewport: { width: 1360, height: 900 } });
  try {
    const auth = await context.request.post(`${BASE_URL}/api/auth`, {
      data: {
        action: "auth:signIn",
        args: {
          provider: "password",
          params: {
            email: "mnote.e2e@example.com",
            password: process.env.MNOTE_E2E_PASSWORD || "MnoteE2E123!",
            flow: "signIn",
          },
        },
      },
    });
    assert(auth.ok(), `登录失败: ${auth.status()} ${await auth.text()}`);
    await assertKnowledgeRagDescriptor(context.request);
    await ensureIndexed(context.request);

    const queryResponse = await context.request.post(`${BASE_URL}/api/knowledge-rag/query`, {
      data: {
        rootUri: ROOT_URI,
        workspaceId: WORKSPACE_ID,
        query: QUERY,
        mode: "mix",
        topK: 8,
        chunkTopK: 8,
        includeChunkContent: true,
        sourcePaths: [EXPECTED_RESOURCE],
      },
    });
    assert(queryResponse.ok(), `knowledge-rag query 失败: ${queryResponse.status()} ${await queryResponse.text()}`);
    const queryPayload = await queryResponse.json();
    const reference = (queryPayload.references || []).find((item) => item.sourceRootRelativePath === EXPECTED_RESOURCE && item.citationUrl);
    assert(reference, `缺少目标引用 ${EXPECTED_RESOURCE}: ${JSON.stringify(queryPayload.references || [], null, 2).slice(0, 3000)}`);
    assert.equal(reference.locatorDegraded, true, `当前 image wrapper 引用应明确降级: ${JSON.stringify(reference, null, 2)}`);
    assert(!reference.locator?.page, `降级引用不应伪造 page: ${JSON.stringify(reference, null, 2)}`);
    assert(!reference.locator?.bbox, `降级引用不应伪造 bbox: ${JSON.stringify(reference, null, 2)}`);
    assert(String(reference.citationUrl || "").includes("resourceTab="), "query citationUrl 缺少 resourceTab");
    assert(String(reference.citationMarkdown || "").includes("来源定位降级"), "query citationMarkdown 缺少降级口径");

    const openResponse = await context.request.post(`${BASE_URL}/api/knowledge-rag/open-reference`, {
      data: {
        rootUri: ROOT_URI,
        workspaceId: WORKSPACE_ID,
        reference: reference.reference,
        filePath: reference.filePath,
        chunkId: reference.chunkId,
      },
    });
    assert(openResponse.ok(), `knowledge-rag open_reference 失败: ${openResponse.status()} ${await openResponse.text()}`);
    const openPayload = await openResponse.json();
    assert.equal(openPayload.ok, true, `open_reference ok=false: ${JSON.stringify(openPayload, null, 2)}`);
    assert.equal(openPayload.reference?.locatorDegraded, true, `open_reference 应保持 locator 降级: ${JSON.stringify(openPayload.reference, null, 2)}`);
    assert(String(openPayload.reference?.citationUrl || "").includes("resourceTab="), "open_reference citationUrl 缺少 resourceTab");
    assert(String(openPayload.reference?.citationMarkdown || "").includes("来源定位降级"), "open_reference citationMarkdown 缺少降级口径");

    const page = await context.newPage();
    const pageErrors = [];
    const consoleErrors = [];
    page.on("pageerror", (error) => pageErrors.push(String(error?.message || error)));
    page.on("console", (message) => {
      if (["error", "warning"].includes(message.type())) consoleErrors.push(`${message.type()}: ${message.text()}`);
    });
    await page.goto(`${BASE_URL}${reference.citationUrl}`, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      (expectedResource) => document.querySelector(`[data-mnote-resource-tab-panel][data-resource-path="${expectedResource}"]`),
      EXPECTED_RESOURCE,
      { timeout: UI_TIMEOUT_MS },
    );
    await page.waitForTimeout(3_000);
    const state = await page.evaluate((expectedResource) => {
      const activeTab = document.querySelector(".mnote-main-tab.is-active, [data-mnote-tab-kind].is-active");
      const panel = document.querySelector(`[data-mnote-resource-tab-panel][data-resource-path="${expectedResource}"]`);
      const inlineViewer = document.querySelector("[data-mnote-inline-pdf-viewer]");
      const evidencePage = document.querySelector("[data-mnote-evidence-page='true']");
      const image = panel ? panel.querySelector("img, [data-mnote-image-viewer], [data-mnote-resource-image]") : null;
      return {
        url: location.href,
        activeTabText: activeTab ? activeTab.textContent.trim().slice(0, 120) : "",
        activeTabKind: activeTab ? activeTab.getAttribute("data-mnote-tab-kind") : "",
        panelVisible: !!panel && !panel.hidden,
        panelResourcePath: panel ? panel.getAttribute("data-resource-path") : "",
        panelLocator: panel ? panel.getAttribute("data-mnote-evidence-locator") : "",
        inlinePdfVisible: !!inlineViewer,
        imageVisible: !!image,
        evidencePageRendered: !!evidencePage,
        evidencePageNumber: evidencePage ? evidencePage.getAttribute("data-page-number") : "",
      };
    }, EXPECTED_RESOURCE);
    await page.screenshot({ path: SCREENSHOT_PATH, fullPage: true });
    assert.equal(state.panelVisible, true, `citationUrl 未打开资源标签页: ${JSON.stringify(state, null, 2)}`);
    assert.equal(state.panelResourcePath, EXPECTED_RESOURCE, `资源标签页路径不匹配: ${JSON.stringify(state, null, 2)}`);
    assert(!String(state.panelLocator || "").includes('"page"'), `降级资源标签页不应携带伪造 page locator: ${JSON.stringify(state, null, 2)}`);

    const result = {
      ok: true,
      baseUrl: BASE_URL,
      rootUri: ROOT_URI,
      workspaceId: WORKSPACE_ID,
      query: QUERY,
      expectedResource: EXPECTED_RESOURCE,
      citationUrl: reference.citationUrl,
      citationMarkdown: reference.citationMarkdown,
      locatorDegraded: reference.locatorDegraded,
      openReferenceCitationUrl: openPayload.reference.citationUrl,
      state,
      pageErrors,
      consoleErrors,
      screenshot: SCREENSHOT_PATH,
    };
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify(result, null, 2)}\n`, "utf8");
    console.log(JSON.stringify(result, null, 2));
  } finally {
    await browser.close().catch(() => undefined);
  }
}

main().catch((error) => {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  fs.writeFileSync(
    path.join(OUTPUT_DIR, "failure.json"),
    `${JSON.stringify({ ok: false, error: error.stack || error.message || String(error) }, null, 2)}\n`,
    "utf8",
  );
  console.error(error.stack || error.message || String(error));
  process.exit(1);
});
