#!/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 = (process.env.MNOTE_WEB_SMOKE_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);
const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
  || ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/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) {
  const metadataDir = path.join(root, ".mnote");
  fs.mkdirSync(metadataDir, { recursive: true });
  fs.writeFileSync(
    path.join(metadataDir, "workspace.json"),
    `${JSON.stringify({
      workspaceId: `local-ws:${ownerId}:task460`,
      ownerId,
      createdAt: new Date().toISOString(),
      capabilities: ["local_files", "markdown_edit", "asset_upload"],
    }, null, 2)}\n`,
    "utf8",
  );
}

async function quickLogin(page) {
  await page.goto(`${BASE_URL}/auth`, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
  const quickLoginButton = page.getByRole("button", { name: "测试账号快速登录" });
  if (await quickLoginButton.count()) {
    await quickLoginButton.click({ timeout: UI_TIMEOUT_MS });
    await page.waitForURL((url) => url.pathname === "/", { timeout: UI_TIMEOUT_MS });
  }
}

async function uploadLocalAsset(page, root, documentId, fileName, mimeType, bytes, kind) {
  return await page.evaluate(
    async ({ rootUri, documentId, fileName, mimeType, bytes, kind }) => {
      const form = new FormData();
      form.append("rootUri", rootUri);
      form.append("documentId", documentId);
      form.append("kind", kind);
      form.append("file", new File([new Uint8Array(bytes)], fileName, { type: mimeType }));
      const response = await fetch("/api/local-folder/assets/upload", { method: "POST", body: form });
      const payload = await response.json().catch(() => null);
      if (!response.ok || !payload || payload.ok !== true) {
        throw new Error(`upload_failed_${response.status}:${JSON.stringify(payload)}`);
      }
      return payload.asset;
    },
    { rootUri: fileUrl(root), documentId, fileName, mimeType, bytes: Array.from(bytes), kind },
  );
}

async function main() {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task460-dirty-close-"));
  const relativePath = "README.md";
  const documentId = localMdDocumentId(relativePath);
  writeWorkspaceManifest(root, "user_real");
  fs.writeFileSync(path.join(root, relativePath), "# Page\n\n页面正文\n", "utf8");

  const browser = await chromium.launch({
    headless: true,
    executablePath: CHROMIUM_EXECUTABLE_PATH,
  });
  const context = await browser.newContext({
    viewport: { width: 1360, height: 900 },
    extraHTTPHeaders: {
      "x-mnote-actor-id": "user_real",
      "x-mnote-actor-type": "user",
    },
  });
  const page = await context.newPage();
  try {
    await quickLogin(page);
    await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });

    // 上传资源文件
    const asset = await uploadLocalAsset(
      page,
      root,
      documentId,
      "report-asset.md",
      "text/markdown",
      Buffer.from("# Report Asset\n\n初始内容\n", "utf8"),
      "attachment",
    );

    // 刷新页面确保资源可读取
    await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });

    // 打开资源 tab
    await page.evaluate(({ asset, documentId }) => {
      window.dispatchEvent(new CustomEvent("tree.asset.open", {
        detail: {
          assetId: asset.id,
          documentId,
          title: asset.file_name || "report-asset.md",
          assetType: asset.asset_type || "attachment",
        },
      }));
    }, { asset, documentId });

    // 等待资源 tab 激活和编辑器就绪
    await page.locator('[data-testid="mnote-resource-tab-host"]:not([hidden])').waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="markdown"]').waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });

    // 验证 tabindex
    const initialTabindex = await page.evaluate(() => {
      const pageTab = document.querySelector('[data-mnote-main-tab="page"]');
      const resourceTab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="markdown"]');
      let inactiveResourceTab = null;
      return {
        pageTabindex: pageTab?.getAttribute('tabindex') || '',
        activeTabindex: resourceTab?.getAttribute('tabindex') || '',
        pageAriaSelected: pageTab?.getAttribute('aria-selected') || '',
        activeAriaSelected: resourceTab?.getAttribute('aria-selected') || '',
      };
    });
    assert.equal(initialTabindex.activeTabindex, '0', `激活的 resource tab 应有 tabindex=0: ${JSON.stringify(initialTabindex)}`);
    assert.equal(initialTabindex.pageTabindex, '-1', `非激活 page tab 应有 tabindex=-1: ${JSON.stringify(initialTabindex)}`);
    assert.equal(initialTabindex.activeAriaSelected, 'true', `激活 tab 应有 aria-selected=true: ${JSON.stringify(initialTabindex)}`);
    assert.equal(initialTabindex.pageAriaSelected, 'false', `非激活 tab 应有 aria-selected=false: ${JSON.stringify(initialTabindex)}`);

    // 编辑内容使 dirty
    const editor = page.locator('.mnote-resource-tab-panel:not([hidden]) .editor-surface .ProseMirror[contenteditable="true"]').first();
    await editor.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.evaluate(() => {
      const editor = document.querySelector('.mnote-resource-tab-panel:not([hidden]) .editor-surface .ProseMirror[contenteditable="true"]');
      if (!(editor instanceof HTMLElement)) throw new Error("resource_editor_missing");
      editor.focus();
      editor.dispatchEvent(new InputEvent("input", {
        bubbles: true,
        cancelable: true,
        inputType: "insertText",
        data: "新添加的未保存内容",
      }));
    });
    await page.waitForTimeout(100);

    // 尝试关闭 dirty 的 resource tab — 应被阻止
    const closeBtn = page.locator('.mnote-main-tab.is-active .mnote-main-tab-close');
    await closeBtn.click({ timeout: UI_TIMEOUT_MS });
    await page.waitForTimeout(300);

    const blockedState = await page.evaluate(() => {
      const activeTab = document.querySelector('.mnote-main-tab.is-active');
      const guardAttr = activeTab?.getAttribute('data-resource-tab-close-guarded') || '';
      const hasGuardClass = activeTab?.classList.contains('is-close-guarded');
      return {
        guardAttr,
        hasGuardClass,
        noticeText: document.querySelector('[data-mnote-resource-close-guard="dirty"]')?.textContent || "",
        tabStillPresent: activeTab !== null,
        kind: activeTab?.getAttribute('data-mnote-tab-kind') || '',
      };
    });
    assert(blockedState.hasGuardClass, `dirty tab 应具有 is-close-guarded class: ${JSON.stringify(blockedState)}`);
    assert.equal(blockedState.guardAttr, 'dirty', `close-guard attribute 应为 dirty: ${JSON.stringify(blockedState)}`);
    assert.equal(blockedState.kind, 'markdown', `dirty tab 关闭阻止后应仍然激活: ${JSON.stringify(blockedState)}`);
    assert.match(blockedState.noticeText, /未保存|保存完成/, `dirty 关闭阻止应显示可见提示: ${JSON.stringify(blockedState)}`);

    // 输入后的短保护窗口内再次关闭仍应被阻止，不应静默释放 resource editor。
    await closeBtn.click({ timeout: UI_TIMEOUT_MS });
    await page.waitForTimeout(100);
    const afterSecondCloseState = await page.evaluate(() => {
      const activeTab = document.querySelector('.mnote-main-tab.is-active');
      return {
        kind: activeTab?.getAttribute('data-mnote-tab-kind') || 'none',
        resourceTabCount: document.querySelectorAll('.mnote-main-tab[data-mnote-tab-kind]:not([data-mnote-tab-kind="page"])').length,
        guardAttr: activeTab?.getAttribute('data-resource-tab-close-guarded') || '',
        noticeCount: document.querySelectorAll('[data-mnote-resource-close-guard="dirty"]').length,
      };
    });
    assert.equal(afterSecondCloseState.kind, 'markdown', `保护窗口内二次关闭后仍应停留在 resource tab: ${JSON.stringify(afterSecondCloseState)}`);
    assert.equal(afterSecondCloseState.resourceTabCount, 1, `保护窗口内 resource tab 不应被移除: ${JSON.stringify(afterSecondCloseState)}`);
    assert.equal(afterSecondCloseState.guardAttr, 'dirty', `保护窗口内应保留 dirty guard: ${JSON.stringify(afterSecondCloseState)}`);
    assert.equal(afterSecondCloseState.noticeCount, 1, `关闭提示不应重复堆叠: ${JSON.stringify(afterSecondCloseState)}`);

    console.log(JSON.stringify({ ok: true, root, assetId: asset.id }, null, 2));
  } finally {
    await context.close().catch(() => undefined);
    await browser.close().catch(() => undefined);
  }
}

main().catch((error) => {
  console.error(error && error.stack ? error.stack : error);
  process.exit(1);
});
