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

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 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",
  );
}

async function main() {
  const suffix = Date.now().toString(36);
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-shared-read-ai-smoke-"));
  const documentId = "local-md:README.md";
  const actorId = "target_user";
  const sessionId = `mnote_shared_read_${suffix}`;
  const runId = `run_shared_read_${suffix}`;
  const rootUri = fileUrl(root);
  const captured = [];

  const browser = await chromium.launch({
    headless: true,
    ...(CHROMIUM_EXECUTABLE_PATH ? { executablePath: CHROMIUM_EXECUTABLE_PATH } : {}),
  });
  const context = await browser.newContext({
    viewport: { width: 1440, height: 960 },
    extraHTTPHeaders: {
      "x-mnote-actor-id": actorId,
      "x-mnote-actor-type": "user",
    },
  });
  const page = await context.newPage();

  try {
    writeWorkspaceManifest(root, actorId, `local-ws:${actorId}:task454`);
    fs.writeFileSync(path.join(root, "README.md"), `# Shared Read Smoke\n只读共享 ${suffix}\n`, "utf8");

    await page.route("**/api/ai-agent/run", async (route) => {
      throw new Error(`页面 AI 不应请求旧 /api/ai-agent/run: ${route.request().url()}`);
    });
    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/hermes/client/profiles", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          active: "reasonix",
          profiles: [{ name: "reasonix", label: "Reasonix", modelConfigured: true, apiKeyConfigured: true }],
        }),
      });
    });
    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: "共享只读会话",
          traceId: `trace_shared_read_${suffix}`,
          persistence: "local_ai_session_jsonl",
          sessionStorage: "local_shared",
          permissionLevel: "shared_read",
          shareId: "share_read_smoke",
        }),
      });
    });
    await page.route(`**/api/hermes/client/sessions/${sessionId}/resume`, async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          sessionId,
          session: { sessionId, messages: [] },
          runtime: { sessionId, runId, status: "completed", profile: "reasonix", documentId },
        }),
      });
    });
    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: 403,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: false,
          code: "local_ai_session_shared_read_write_forbidden",
          message: "共享只读 AI 会话不能写入正文",
          permissionLevel: "shared_read",
          shareId: "share_read_smoke",
        }),
      });
    });

    const documentUrl = new URL(`${BASE_URL}/documents/${encodeURIComponent(documentId)}`);
    documentUrl.searchParams.set("sourceKind", "local_folder");
    documentUrl.searchParams.set("rootUri", rootUri);
    await page.goto(documentUrl.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      () => (document.body.textContent || "").includes("Shared Read Smoke"),
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]').first().waitFor({
      state: "attached",
      timeout: UI_TIMEOUT_MS,
    }).catch(() => undefined);

    await page.getByTestId("wolai-floating-ai").click({ timeout: UI_TIMEOUT_MS });
    await page.locator("[data-page-ai-input]").fill("请修改共享只读页面正文", { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      () => {
        const drawerText = document.querySelector('[data-testid="wolai-page-ai-drawer"]')?.textContent || "";
        return drawerText.includes("共享只读 AI 会话不能写入正文")
          || drawerText.includes("local_ai_session_shared_read_write_forbidden");
      },
      null,
      { timeout: UI_TIMEOUT_MS },
    );

    const readme = fs.readFileSync(path.join(root, "README.md"), "utf8");
    assert(!readme.includes("请修改共享只读页面正文"), "共享只读 smoke 不应写入 README.md");
    assert(captured.some((entry) => entry.kind === "run"), "未捕获 page AI run 请求");
    console.log(JSON.stringify({
      ok: true,
      root,
      documentId,
      sessionId,
      runId,
      capturedKinds: captured.map((entry) => entry.kind),
    }, null, 2));
  } finally {
    await context.close().catch(() => undefined);
    await browser.close().catch(() => undefined);
    fs.rmSync(root, { recursive: true, force: true });
  }
}

main().catch((error) => {
  console.error(error instanceof Error ? error.stack || error.message : String(error));
  process.exit(1);
});
