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

const assert = require("node:assert/strict");
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 writeWorkspaceManifest(root) {
  const metadataDir = path.join(root, ".mnote");
  fs.mkdirSync(metadataDir, { recursive: true });
  fs.writeFileSync(
    path.join(metadataDir, "workspace.json"),
    `${JSON.stringify({
      workspaceId: "local-ws:user_real:task464",
      ownerId: "user_real",
      createdAt: new Date().toISOString(),
      capabilities: ["local_files", "tree_commands", "markdown_edit", "asset_upload"],
    }, null, 2)}\n`,
    "utf8",
  );
}

async function postTreeCommand(rootUri, action, documentId) {
  const response = await fetch(`${BASE_URL}/api/tree/commands`, {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "x-mnote-actor-id": "user_real",
      "x-mnote-actor-type": "user",
    },
    body: JSON.stringify({
      action,
      sourceKind: "local_folder",
      rootUri,
      documentId,
    }),
  });
  const payload = await response.json().catch(async () => ({ text: await response.text() }));
  assert.equal(response.status, 200, `${action} failed: ${JSON.stringify(payload)}`);
  return payload;
}

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 openTrash(page, rootUri) {
  const url = new URL(`${BASE_URL}/trash`);
  url.searchParams.set("sourceKind", "local_folder");
  url.searchParams.set("rootUri", rootUri);
  await page.goto(url.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
  await page.locator('[data-testid="mnote-trash-workbench"][data-trash-source-kind="local_folder"]').waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
}

async function main() {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task464-trash-ui-"));
  const rootUri = fileUrl(root);
  const assetId = "local-file:docs/资源.txt";
  const sourcePath = path.join(root, "docs", "资源.txt");
  const trashIndexPath = path.join(root, ".mnote", "trash-index.json");
  fs.mkdirSync(path.join(root, "docs"), { recursive: true });
  writeWorkspaceManifest(root);
  fs.writeFileSync(path.join(root, "README.md"), "# Local Root\n", "utf8");
  fs.writeFileSync(sourcePath, "asset body", "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);

    const archived = await postTreeCommand(rootUri, "delete", assetId);
    assert.equal(archived.result?.execution?.canonicalCommand, "tree.resource.archive");
    assert.equal(fs.existsSync(sourcePath), false, "archive 后源文件应移入垃圾箱");

    await openTrash(page, rootUri);
    const row = page.locator(`article[data-trash-row="local"][data-trash-entry-id="${assetId}"]`);
    await row.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await row.getByRole("button", { name: "恢复" }).click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => !document.querySelector('[data-trash-entry-id="local-file:docs/资源.txt"]'), null, {
      timeout: UI_TIMEOUT_MS,
    });
    assert.equal(fs.existsSync(sourcePath), true, "UI restore 后源文件应恢复");

    await postTreeCommand(rootUri, "delete", assetId);
    await openTrash(page, rootUri);
    const rowAgain = page.locator(`article[data-trash-row="local"][data-trash-entry-id="${assetId}"]`);
    await rowAgain.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    page.once("dialog", (dialog) => dialog.accept());
    await rowAgain.getByRole("button", { name: "彻底删除" }).click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => !document.querySelector('[data-trash-entry-id="local-file:docs/资源.txt"]'), null, {
      timeout: UI_TIMEOUT_MS,
    });
    assert.equal(fs.existsSync(sourcePath), false, "UI purge 后源文件不应恢复");
    const index = fs.existsSync(trashIndexPath) ? fs.readFileSync(trashIndexPath, "utf8") : "";
    assert.doesNotMatch(index, /local-file:docs\/资源\.txt/, "UI purge 后 trash index 应清理 entry");

    console.log(JSON.stringify({ ok: true, root, assetId }, 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 && error.stack ? error.stack : error);
  process.exit(1);
});
