#!/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 = "task535-page-ai-local-agent-clean-edit-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 },
  );
}

function parseJsonBody(record) {
  try {
    return JSON.parse(record.body || "{}");
  } catch (error) {
    throw new Error(`无法解析 JSON body: ${error instanceof Error ? error.message : String(error)}`);
  }
}

async function main() {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const suffix = Date.now().toString(36);
  const actorId = "mnote-e2e";
  const workspaceId = `local-ws:${actorId}:task535`;
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task535-agent-clean-"));
  const rootUri = fileUrl(root);
  const relativePath = "AgentClean.md";
  const documentId = localMdDocumentId(relativePath);
  const filePath = path.join(root, relativePath);
  const initialToken = `task535-initial-${suffix}`;
  const patchedToken = `task535-agent-patched-${suffix}`;
  const runId = `run_task535_${suffix}`;
  const sessionId = `mnote_task535_${suffix}`;
  const captured = [];
  const blockedRequests = [];
  let eventStreamRequested = false;
  let caughtError = null;

  writeWorkspaceManifest(root, actorId, workspaceId);
  fs.writeFileSync(
    filePath,
    ["# Agent Clean", "", initialToken, ""].join("\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",
    },
  });
  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/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_task535_${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, status: "mocked" },
          profile: { name: "reasonix", modelConfigured: true, apiKeyConfigured: true },
          suggestions: [],
        }),
      });
    });
    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: [
            { profileId: "shared_gemini_chat", kind: "shared", displayName: "Gemini Chat", canRun: true, readonly: true },
            { profileId: "usr_task535_default", kind: "personal", displayName: "我的 Hermes", baseProfile: "default", isolatedProfile: "mnote-u-task535-default", canRun: true },
          ],
        }),
      });
    });
    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,
          title: "task535",
          traceId: `trace_task535_session_${suffix}`,
          persistence: "local_ai_session_jsonl",
          sessionStorage: "local_private",
        }),
      });
    });
    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: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          sessionId,
          runId,
          events: [],
          traceId: `trace_task535_run_${suffix}`,
        }),
      });
    });
    await page.route("**/api/hermes/client/events/*", async (route) => {
      eventStreamRequested = true;
      fs.writeFileSync(
        filePath,
        ["# Agent Clean", "", initialToken, "", patchedToken, ""].join("\n"),
        "utf8",
      );
      const completed = {
        event: "run.completed",
        run_id: runId,
        output: "Task535 response",
        agentAudit: {
          rootUri,
          actorId,
          actorType: "user",
          agentKind: "reasonix",
          changedFiles: [{ path: relativePath, changeType: "modified", summary: "task535 native file patch" }],
          agentRunReceipt: {
            schema: "mnote.agent_run_receipt.v1",
            runId,
            sessionId,
            workspaceId,
            documentId,
            rootUri,
            agentKind: "reasonix",
            status: "completed",
            permission: "write",
            changedFiles: [{ path: relativePath, changeType: "modified", summary: "task535 native file patch" }],
            refresh: {
              touchesCurrentFile: true,
              currentDocumentId: documentId,
              strategy: "refresh_current_file",
            },
          },
        },
      };
      await route.fulfill({
        status: 200,
        headers: { "content-type": "text/event-stream; charset=utf-8" },
        body:
          `data: ${JSON.stringify({ event: "message.delta", run_id: runId, delta: "Task535 response" })}\n\n`
          + `data: ${JSON.stringify(completed)}\n\n`,
      });
    });

    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 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("请用原生文件编辑能力追加 task535 标记", { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS });

    await page.waitForFunction(
      () => (document.querySelector('[data-testid="wolai-page-ai-drawer"]')?.textContent || "").includes("Task535 response"),
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    await page.waitForFunction(
      () => document.documentElement.getAttribute("data-mnote-page-ai-receipt-current-refresh") === "true"
        && document.documentElement.getAttribute("data-mnote-page-ai-receipt-filetree-refresh") === "true",
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    await waitForEditorText(page, patchedToken);

    const runs = captured.filter((item) => item.kind === "run");
    assert.strictEqual(runs.length, 1, `应只启动一次 Page AI run，实际 ${runs.length}`);
    assert(eventStreamRequested, "Page AI run 应继续读取 SSE events");
    const runBody = parseJsonBody(runs[0]);
    assert.strictEqual(runBody.sourceKind, "local_folder", `run sourceKind 应为 local_folder: ${JSON.stringify(runBody)}`);
    assert.strictEqual(runBody.rootUri, rootUri, `run rootUri 应指向测试工作区: ${JSON.stringify(runBody)}`);
    assert.strictEqual(runBody.targetPackage?.schema, "mnote.agent_target_package.v1", "run payload 应携带 targetPackage");
    assert.strictEqual(runBody.targetPackage?.currentFile?.relativePath, relativePath, `currentFile 应指向当前 Markdown: ${JSON.stringify(runBody.targetPackage)}`);
    assert(runBody.targetPackage?.allowedFiles?.includes(relativePath), `allowedFiles 应包含当前 Markdown: ${JSON.stringify(runBody.targetPackage?.allowedFiles)}`);
    assert.strictEqual(
      runBody.targetPackage?.targets?.[0]?.policy?.permission,
      "read_write",
      `write grant 下 target policy 应为 read_write: ${JSON.stringify(runBody.targetPackage?.targets?.[0]?.policy)}`,
    );
    const serializedRunBody = JSON.stringify(runBody);
    const usedMarkdownEdit = serializedRunBody.includes("mnote.doc.markdown_edit");
    const usedPageSave = serializedRunBody.includes("mnote.page.save");
    const usedDocumentsSave = blockedRequests.length > 0;
    assert(!usedMarkdownEdit, "local-first 普通 Markdown run payload 不应要求 mnote.doc.markdown_edit");
    assert(!usedPageSave, "local-first 普通 Markdown run payload 不应要求 mnote.page.save");
    assert(!usedDocumentsSave, `clean agent 原生文件编辑 smoke 不应调用页面保存接口: ${JSON.stringify(blockedRequests)}`);
    const finalDiskContent = fs.readFileSync(filePath, "utf8");
    assert(finalDiskContent.includes(patchedToken), "磁盘文件应包含 agent 原生写入内容");

    const screenshot = await saveScreenshot(page, "01-clean-agent-edit");
    const result = {
      ok: true,
      task: TASK,
      baseUrl: BASE_URL,
      root,
      rootUri,
      documentId,
      relativePath,
      patchedToken,
      screenshot,
      captured,
      blockedRequests,
      usedDocumentsSave,
      usedMarkdownEdit,
      usedPageSave,
      currentRefresh: true,
      filetreeRefresh: true,
      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);
  });
}
