#!/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 = "task536-page-ai-local-agent-dirty-guard-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 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", "ai_sessions", "markdown_edit"],
    }, null, 2)}\n`,
    "utf8",
  );
}

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(OUTPUT_DIR, `${name}.png`);
  await page.screenshot({ path: target, fullPage: false });
  return target;
}

async function waitForEditorText(page, expected) {
  await page.waitForFunction(
    (text) => {
      const editor = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"] .ProseMirror');
      return (editor?.textContent || "").includes(text);
    },
    expected,
    { timeout: UI_TIMEOUT_MS },
  );
}

async function waitForEditorStatus(page, expected) {
  await page.waitForFunction(
    (status) => {
      const root = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
      return root?.getAttribute("data-runtime-editor-status") === status;
    },
    expected,
    { timeout: UI_TIMEOUT_MS },
  );
}

async function typeDirtyText(page, text) {
  const editor = page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"] .ProseMirror').first();
  await editor.click({ timeout: UI_TIMEOUT_MS });
  await page.keyboard.type(text, { delay: 5 });
  await waitForEditorText(page, text.trim());
}

async function main() {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const suffix = Date.now().toString(36);
  const actorId = "mnote-e2e";
  const workspaceId = `local-ws:${actorId}:task536`;
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task536-dirty-"));
  const rootUri = fileUrl(root);
  const relativePath = "DirtyGuard.md";
  const documentId = localMdDocumentId(relativePath);
  const filePath = path.join(root, relativePath);
  const initialToken = `task536-initial-${suffix}`;
  const dirtyToken = `task536-dirty-${suffix}`;
  const forbiddenToken = `task536-forbidden-${suffix}`;
  const captured = [];
  const blockedRequests = [];
  const bufferStateRequests = [];
  let forceDirtyState = false;
  let caughtError = null;

  writeWorkspaceManifest(root, actorId, workspaceId);
  fs.writeFileSync(
    filePath,
    ["# Dirty Guard", "", initialToken, ""].join("\n"),
    "utf8",
  );
  const originalDiskContent = fs.readFileSync(filePath, "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",
    },
  });
  const page = await context.newPage();

  page.on("request", (request) => {
    const url = request.url();
    if (url.includes("/api/documents/save") || url.includes("/api/page-body/write")) {
      blockedRequests.push({ url, method: request.method(), body: request.postData() || "" });
    }
  });

  try {
    await page.route("**/api/documents/buffer-state?**", async (route) => {
      bufferStateRequests.push(route.request().url());
      if (!forceDirtyState) {
        await route.continue();
        return;
      }
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          result: {
            documentId,
            sourceKind: "local_folder",
            rootUri,
            relativePath,
            dirtyState: "Dirty",
            externalActor: null,
            fileVersion: `task536-dirty-buffer-${suffix}`,
          },
        }),
      });
    });
    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_task536_${suffix}`,
            userId: actorId,
            workspaceId,
            rootUri,
            rootPath: root,
            permission: "write",
            recursive: true,
            capabilities: ["ai", "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: {} }) });
    });
    await page.route("**/api/hermes/client/gateway/health**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true, gateway: { ok: true }, profile: { name: "reasonix", modelConfigured: true, apiKeyConfigured: true } }),
      });
    });
    await page.route("**/api/hermes/client/tools**", async (route) => {
      await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, tools: [] }) });
    });
    await page.route("**/api/ai/agent-profiles**", async (route) => {
      await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, agentId: "reasonix", profiles: [] }) });
    });
    await page.route("**/api/hermes/client/profiles**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true, active: "mnoteai", profiles: [{ name: "mnoteai", label: "MNote AI", modelConfigured: true, apiKeyConfigured: true }] }),
      });
    });
    await page.route("**/api/hermes/client/skills**", async (route) => {
      await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, categories: [], archived: [] }) });
    });
    await page.route("**/api/hermes/client/capabilities**", async (route) => {
      await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, runtime: "mnote", categories: [], archived: [] }) });
    });
    await page.route("**/api/hermes/client/sessions", async (route) => {
      captured.push({ kind: "session", method: route.request().method(), body: route.request().postData() || "" });
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true, sessionId: `mnote_task536_${suffix}`, title: "task536", traceId: `trace_task536_session_${suffix}` }),
      });
    });
    await page.route("**/api/hermes/client/runs", async (route) => {
      captured.push({ kind: "run", method: route.request().method(), body: route.request().postData() || "" });
      await route.fulfill({
        status: 500,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: false, code: "task536_runs_should_not_be_called" }),
      });
    });

    await ensureAuthenticated(page, context.request);
    const response = await page.goto(documentUrl(root, relativePath), {
      waitUntil: "domcontentloaded",
      timeout: UI_TIMEOUT_MS,
    });
    assert(response && response.status() === 200, `文档页状态码异常: ${response && response.status()}`);
    await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"] .ProseMirror').first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    await waitForEditorText(page, initialToken);
    await typeDirtyText(page, ` ${dirtyToken}`);
    await waitForEditorStatus(page, "dirty");
    forceDirtyState = true;

    await page.getByTestId("wolai-floating-ai").click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="wolai-page-ai-drawer"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.locator("[data-page-ai-input]").fill(`请新增 ${forbiddenToken}`, { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      () => document.documentElement.getAttribute("data-mnote-page-ai-run-status") === "failed"
        && (document.querySelector('[data-testid="wolai-page-ai-drawer"]')?.textContent || "").includes("未保存或外部变更"),
      null,
      { timeout: UI_TIMEOUT_MS },
    );

    const runs = captured.filter((item) => item.kind === "run");
    const blockedBeforeRun = runs.length === 0;
    assert(blockedBeforeRun, `dirty buffer 应在 /runs 前被拦截，实际捕获 ${runs.length} 次 run`);
    assert(bufferStateRequests.length >= 1, "dirty guard 应查询 /api/documents/buffer-state");
    assert.strictEqual(blockedRequests.length, 0, `dirty guard 不应调用页面写入接口: ${JSON.stringify(blockedRequests)}`);
    const finalDiskContent = fs.readFileSync(filePath, "utf8");
    const diskChanged = finalDiskContent !== originalDiskContent;
    const editorDirtyTextStillVisible = await page.evaluate(
      (expected) => (document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"] .ProseMirror')?.textContent || "").includes(expected),
      dirtyToken,
    );
    assert(!diskChanged, "dirty guard 后磁盘内容必须保持不变");
    assert(editorDirtyTextStillVisible, "dirty guard 后编辑器中未保存内容应仍可见");
    assert(!finalDiskContent.includes(forbiddenToken), "dirty guard 后磁盘不应包含 forbidden token");

    const screenshot = await saveScreenshot(page, "01-dirty-guard");
    const result = {
      ok: true,
      task: TASK,
      baseUrl: BASE_URL,
      root,
      rootUri,
      documentId,
      relativePath,
      dirtyToken,
      forbiddenToken,
      screenshot,
      captured,
      blockedRequests,
      bufferStateRequests,
      blockedBeforeRun,
      diskChanged,
      editorDirtyTextStillVisible,
      finalDiskContent,
    };
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify(result, null, 2)}\n`, "utf8");
    console.log(JSON.stringify(result, null, 2));
  } catch (error) {
    caughtError = error;
    await saveScreenshot(page, "failure").catch(() => undefined);
  } finally {
    await page.close().catch(() => undefined);
    await context.close().catch(() => undefined);
    await browser.close().catch(() => undefined);
  }

  if (caughtError) {
    throw caughtError;
  }
}

if (require.main === module) {
  main().catch((error) => {
    console.error(error);
    process.exit(1);
  });
}
