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

const assert = require("node:assert");
const { chromium } = require("playwright");
const {
  BASE_URL,
  UI_TIMEOUT_MS,
  cleanupDocuments,
  createTempDocument,
  ensureAuthenticated,
  renameDocument,
} = require("./tree-shell-smoke-helpers");

async function main() {
  const suffix = Date.now().toString(36);
  const title = `TEST-HERMES-AI-agent-skill-${suffix}`;
  const runId = `run_agent_skill_${suffix}`;
  const createdIds = [];
  const sessionBodies = [];
  const runBodies = [];
  const activeProfileBodies = [];
  const memorySaveBodies = [];
  const skillToggleBodies = [];
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
  const page = await context.newPage();

  try {
    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/profiles/active", async (route) => {
      activeProfileBodies.push(JSON.parse(route.request().postData() || "{}"));
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true, profile: { name: "chemist", active: 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,
          profiles: [
            { name: "default", active: true, model: "gpt-5", gateway: "openai", alias: "Default" },
            { name: "chemist", active: false, model: "gpt-5", gateway: "openai", alias: "Chemist" },
          ],
        }),
      });
    });
    await page.route("**/api/hermes/client/profile-memory**", async (route) => {
      if (route.request().method() === "POST") {
        memorySaveBodies.push(JSON.parse(route.request().postData() || "{}"));
        await route.fulfill({
          status: 200,
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ ok: true }),
        });
        return;
      }
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          memory: "长期记忆",
          user: "用户偏好",
          soul: "原始人格",
          memory_mtime: Date.now(),
          user_mtime: Date.now(),
          soul_mtime: Date.now(),
        }),
      });
    });
    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: [
            {
              name: "writing",
              description: "Writing helpers",
              skills: [
                {
                  name: "ai-writing-detection",
                  description: "检测 AI 写作痕迹",
                  enabled: false,
                  source: "local",
                },
              ],
            },
          ],
          archived: [],
        }),
      });
    });
    await page.route("**/api/hermes/client/skills/toggle", async (route) => {
      skillToggleBodies.push(JSON.parse(route.request().postData() || "{}"));
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true }),
      });
    });
    await page.route("**/api/hermes/client/sessions", async (route) => {
      const body = JSON.parse(route.request().postData() || "{}");
      sessionBodies.push(body);
      const profile = body.profile || "default";
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          sessionId: `mnote_${profile}_${suffix}`,
          title: "当前页问答",
          profile,
          traceId: `trace_session_${suffix}`,
          persistence: "hermes_on_first_run",
        }),
      });
    });
    await page.route("**/api/hermes/client/sessions/**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          session: {
            sessionId: `mnote_chemist_${suffix}`,
            profile: "chemist",
            messages: [],
          },
        }),
      });
    });
    await page.route("**/api/hermes/client/runs", async (route) => {
      runBodies.push(JSON.parse(route.request().postData() || "{}"));
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true, runId, sessionId: `mnote_chemist_${suffix}` }),
      });
    });
    await page.route(`**/api/hermes/client/events/${runId}`, async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "text/event-stream; charset=utf-8" },
        body:
          `data: ${JSON.stringify({ event: "message.delta", run_id: runId, session_id: `mnote_chemist_${suffix}`, delta: "Agent " })}\n\n` +
          `data: ${JSON.stringify({ event: "run.completed", run_id: runId, session_id: `mnote_chemist_${suffix}`, output: "Agent response" })}\n\n`,
      });
    });

    await ensureAuthenticated(page, context.request);
    const target = await createTempDocument(context.request);
    createdIds.push(target.documentId);
    await renameDocument(context.request, target.workspaceId, target.documentId, title);
    await page.goto(
      `${BASE_URL}/documents/${encodeURIComponent(target.documentId)}?workspaceId=${encodeURIComponent(target.workspaceId)}`,
      { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS },
    );

    await page.getByTestId("wolai-floating-ai").click({ timeout: UI_TIMEOUT_MS });
    await page.locator("[data-page-ai-profile-select]").selectOption("chemist", { timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => document.documentElement.getAttribute("data-mnote-page-ai-profile") === "chemist", null, {
      timeout: UI_TIMEOUT_MS,
    });

    await page.locator('[data-page-ai-tab="agent"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-memory-editor="soul"]').fill(`SOUL-${suffix}`, { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-memory-save="soul"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => document.documentElement.getAttribute("data-mnote-page-ai-memory-saved") === "soul", null, {
      timeout: UI_TIMEOUT_MS,
    });

    await page.locator('[data-page-ai-tab="skills"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator("[data-page-ai-skill-search]").fill("writing", { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-skill-toggle="ai-writing-detection"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      () => document.documentElement.getAttribute("data-mnote-page-ai-skill-toggled") === "ai-writing-detection",
      null,
      { timeout: UI_TIMEOUT_MS },
    );

    await page.locator('[data-page-ai-tab="chat"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator("[data-page-ai-input]").fill(`请使用 chemist agent 总结 ${title}`, { 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("Agent response"),
      null,
      { timeout: UI_TIMEOUT_MS },
    );

    assert(activeProfileBodies.some((body) => body.name === "chemist"), "选择 agent/profile 必须调用 Hermes active profile API");
    assert(memorySaveBodies.some((body) => body.section === "soul" && body.content === `SOUL-${suffix}`), "SOUL.md 保存必须调用 Hermes memory API");
    assert(
      skillToggleBodies.some((body) => body.name === "ai-writing-detection" && body.enabled === true),
      "skill 启用必须调用 Hermes skills toggle API",
    );
    assert(runBodies.some((body) => body.profile === "chemist"), "Hermes run 必须携带当前 agent/profile");
    assert(sessionBodies.some((body) => body.profile === "chemist"), "切换 agent 后新 Hermes session 必须携带 profile");

    console.log(
      JSON.stringify(
        {
          ok: true,
          baseUrl: BASE_URL,
          documentId: target.documentId,
          workspaceId: target.workspaceId,
          profile: "chemist",
          memorySectionsSaved: memorySaveBodies.map((body) => body.section),
          skillsToggled: skillToggleBodies.map((body) => body.name),
          runProfiles: runBodies.map((body) => body.profile),
        },
        null,
        2,
      ),
    );
  } finally {
    await cleanupDocuments(context.request, createdIds).catch(() => undefined);
    await context.close().catch(() => undefined);
    await browser.close().catch(() => undefined);
  }
}

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