#!/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,
  ensureAuthenticated,
} = require("./tree-shell-smoke-helpers");

const TASK = "task540-local-folder-event-bus-single-connection-smoke";
const OUTPUT_DIR = path.join(process.cwd(), "tmp", TASK);
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));
  url.searchParams.set("treeView", "filetree");
  return url.toString();
}

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

async function main() {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const suffix = Date.now().toString(36);
  const actorId = "mnote-e2e";
  const workspaceId = `local-ws:${actorId}:task540`;
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task540-event-bus-"));
  const rootUri = fileUrl(root);
  const relativePath = "EventBus.md";
  const resourcePath = "Attachment.bin";
  const filePath = path.join(root, relativePath);
  const resourceFilePath = path.join(root, resourcePath);
  writeWorkspaceManifest(root, actorId, workspaceId);
  fs.writeFileSync(filePath, `# Event Bus\n\ntask540-${suffix}\n`, "utf8");
  fs.writeFileSync(resourceFilePath, `task540-resource-${suffix}\n`, "utf8");

  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",
    extraHTTPHeaders: {
      "x-mnote-actor-id": actorId,
      "x-mnote-actor-type": "user",
    },
  });
  await context.addInitScript(() => {
    const sources = [];
    const originalFetch = window.fetch.bind(window);
    window.__mnoteTask540StatRequests = [];
    window.__mnoteTask540FileProjectionRequests = [];
    window.__mnoteTask540SidebarProjectionRequests = [];
    window.fetch = function patchedTask540Fetch(input, init) {
      const url = typeof input === "string" ? input : String(input?.url || "");
      if (url.includes("/api/local-folder/files/stat")) {
        window.__mnoteTask540StatRequests.push(url);
      }
      if (url.includes("/api/tree/projections/file")) {
        window.__mnoteTask540FileProjectionRequests.push(url);
      }
      if (url.includes("/api/tree/projections/sidebar")) {
        window.__mnoteTask540SidebarProjectionRequests.push(url);
      }
      return originalFetch(input, init);
    };
    class FakeEventSource {
      constructor(input) {
        this.url = String(input || "");
        this.readyState = 0;
        this.listeners = new Map();
        sources.push(this);
        setTimeout(() => this.dispatch("open", {}), 0);
      }
      addEventListener(name, handler) {
        if (!this.listeners.has(name)) this.listeners.set(name, []);
        this.listeners.get(name).push(handler);
      }
      removeEventListener(name, handler) {
        const list = this.listeners.get(name) || [];
        this.listeners.set(name, list.filter((candidate) => candidate !== handler));
      }
      dispatch(name, payload) {
        const event = { data: JSON.stringify(payload || {}), lastEventId: String(payload?.revision || "") };
        (this.listeners.get(name) || []).forEach((handler) => handler(event));
      }
      close() {
        this.readyState = 2;
      }
    }
    window.EventSource = FakeEventSource;
    window.__mnoteTask540EventSources = sources;
    window.__mnoteTask540CompatEvents = [];
    window.addEventListener("tree:local-folder-watch-batch", (event) => {
      window.__mnoteTask540CompatEvents.push(event.detail || {});
    });
  });

  const page = await context.newPage();
  const statRequests = [];
  page.on("request", (request) => {
    const url = request.url();
    if (url.includes("/api/local-folder/files/stat")) {
      statRequests.push(url);
    }
  });
  await page.route("**/api/user/access-policy**", async (route) => {
    await route.fulfill({
      status: 200,
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        ok: true,
        controlPlane: "sqlite",
        grants: [{
          id: `grant_task540_${suffix}`,
          userId: actorId,
          workspaceId,
          rootUri,
          rootPath: root,
          permission: "write",
          recursive: true,
          capabilities: ["markdown_edit"],
          source: "user",
          status: "active",
        }],
      }),
    });
  });
  await page.route("**/api/ui/preferences**", async (route) => {
    await route.fulfill({
      status: 200,
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ ok: true, owner: "mnote-web", result: {} }),
    });
  });

  try {
    await ensureAuthenticated(page, context.request);
    await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => window.__mnoteLocalFolderEventBus, null, { timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => {
      const sources = window.__mnoteTask540EventSources || [];
      return sources.filter((source) => String(source.url || "").includes("/api/local-folder/events")).length === 1;
    }, null, { timeout: UI_TIMEOUT_MS });

    await page.waitForFunction(() => window.__mnoteDocumentPaneRuntime?.openResourceInActiveTab, null, { timeout: UI_TIMEOUT_MS });
    const openedResource = await page.evaluate(async ({ rootUriValue, pathValue, workspaceIdValue }) => {
      const href = new URL("/api/local-folder/resource/read", window.location.origin);
      href.searchParams.set("rootUri", rootUriValue);
      href.searchParams.set("path", pathValue);
      return await window.__mnoteDocumentPaneRuntime.openResourceInActiveTab({
        objectIdentity: `local-resource:${pathValue}`,
        assetId: `task540:${pathValue}`,
        title: pathValue,
        fileName: pathValue,
        kind: "file",
        sourceKind: "local_folder",
        rootUri: rootUriValue,
        workspaceId: workspaceIdValue,
        path: pathValue,
        href: href.toString(),
      });
    }, { rootUriValue: rootUri, pathValue: resourcePath, workspaceIdValue: workspaceId });
    assert.equal(openedResource, true, "resource tab 应能打开");
    await page.waitForFunction(() => {
      const panel = document.querySelector('.mnote-resource-tab-panel[data-resource-path="Attachment.bin"]');
      return panel?.getAttribute("data-mnote-resource-watch-ready") === "event-bus";
    }, null, { timeout: UI_TIMEOUT_MS });

    await page.evaluate(() => {
      window.__mnoteTask540StatRequests = [];
      window.__mnoteTask540FileProjectionRequests = [];
      window.__mnoteTask540SidebarProjectionRequests = [];
    });
    await page.evaluate(({ rootUriValue, pagePath, assetPath }) => {
      const detail = {
        source: "synthetic_page_ai_receipt",
        reason: "agent_run_receipt",
        rootUri: rootUriValue,
        payload: {
          schema: "mnote.local_folder.watch_batch.v1",
          source: "agent_run_receipt",
          rootUri: rootUriValue,
          revision: "task540-revision",
          changedPaths: [
            { relativePath: pagePath, changeType: "modified" },
            { relativePath: assetPath, changeType: "modified" },
          ],
          affectedParents: [{ relativePath: "", reason: "task540" }],
        },
      };
      window.__mnoteLocalFolderEventBus.emitSyntheticWatchBatch(detail);
      window.__mnoteLocalFolderEventBus.emitSyntheticWatchBatch(detail);
    }, { rootUriValue: rootUri, pagePath: relativePath, assetPath: resourcePath });

    await page.waitForFunction(() => {
      const events = window.__mnoteTask540CompatEvents || [];
      return events.some((event) => event?.source === "synthetic_page_ai_receipt" && event?.viaEventBus === true);
    }, null, { timeout: UI_TIMEOUT_MS });
    await page.waitForFunction((pathValue) => {
      const urls = window.__mnoteTask540StatRequests || [];
      return urls.some((url) => String(url).includes(encodeURIComponent(pathValue)) || String(url).includes(pathValue));
    }, resourcePath, { timeout: 3000 }).catch(() => undefined);
    await page.waitForFunction(() => {
      const urls = window.__mnoteTask540FileProjectionRequests || [];
      return urls.length >= 1;
    }, null, { timeout: UI_TIMEOUT_MS });

    const result = await page.evaluate(() => {
      const sources = (window.__mnoteTask540EventSources || [])
        .filter((source) => String(source.url || "").includes("/api/local-folder/events"))
        .map((source) => source.url);
      const compatEvents = window.__mnoteTask540CompatEvents || [];
      const resourcePanel = document.querySelector('.mnote-resource-tab-panel[data-resource-path="Attachment.bin"]');
      return {
        sources,
        busState: document.documentElement.getAttribute("data-mnote-local-folder-event-bus") || "",
        connectionCount: document.documentElement.getAttribute("data-mnote-local-folder-event-bus-connections") || "",
        lastSource: document.documentElement.getAttribute("data-mnote-local-folder-event-bus-last-source") || "",
        lastReason: document.documentElement.getAttribute("data-mnote-local-folder-event-bus-last-reason") || "",
        compatEventCount: compatEvents.length,
        lastCompatViaEventBus: Boolean(compatEvents.at(-1)?.viaEventBus),
        hasPageAiSyntheticCompatEvent: compatEvents.some((event) => (
          event?.source === "synthetic_page_ai_receipt"
          && event?.reason === "agent_run_receipt"
          && event?.viaEventBus === true
        )),
        resourceWatchReady: resourcePanel?.getAttribute("data-mnote-resource-watch-ready") || "",
        browserStatRequests: window.__mnoteTask540StatRequests || [],
        fileProjectionRequests: window.__mnoteTask540FileProjectionRequests || [],
        sidebarProjectionRequests: window.__mnoteTask540SidebarProjectionRequests || [],
      };
    });

    assert.equal(result.sources.length, 1, `同一页面应只有一个 local-folder EventSource，实际 ${result.sources.length}`);
    assert.equal(result.busState, "ready", "event bus diagnostics 未 ready");
    assert.equal(result.connectionCount, "1", "event bus diagnostics connectionCount 应为 1");
    assert.equal(result.hasPageAiSyntheticCompatEvent, true, "Page AI synthetic 事件应保留 source/reason 并通过 bus 派发兼容事件");
    assert.equal(result.lastCompatViaEventBus, true, "兼容 tree:local-folder-watch-batch 必须标记 viaEventBus");
    assert.equal(result.resourceWatchReady, "event-bus", "resource tab watch 应通过 event bus 准备好");
    assert(
      result.browserStatRequests.some((url) => String(url).includes(encodeURIComponent(resourcePath)) || String(url).includes(resourcePath)),
      "resource-changed 应触发当前资源 stat 刷新",
    );
    assert.equal(result.fileProjectionRequests.length, 1, "同 tick 两个 receipt 应只触发一次 filetree parent projection 刷新");
    assert.equal(result.sidebarProjectionRequests.length, 0, "content-only receipt 不应触发 sidebar projection 刷新");

    fs.writeFileSync(RESULT_PATH, `${JSON.stringify({ ok: true, root, result, statRequests }, null, 2)}\n`, "utf8");
    console.log(`[${TASK}] ok`, RESULT_PATH);
  } finally {
    await browser.close();
  }
}

main().catch((error) => {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  fs.writeFileSync(RESULT_PATH, `${JSON.stringify({ ok: false, error: error.stack || String(error) }, null, 2)}\n`, "utf8");
  console.error(`[${TASK}] failed`, error);
  process.exit(1);
});
