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

const assert = require("node:assert");
const fs = require("node:fs/promises");
const path = require("node:path");
const { chromium } = require("playwright");

const ROOT = path.resolve(__dirname, "..");
const BASE_URL = (process.env.MNOTE_UI_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 OUT_DIR = path.join(ROOT, "tmp", "task439-filetree-title-md-rename-smoke");

function cssString(value) {
  return String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
}

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 openFileTree(page) {
  await page.evaluate(() => {
    const tab = document.querySelector('[data-mnote-sidebar-tree-tab="filetree"], button[aria-label="文件"]');
    if (tab instanceof HTMLElement) tab.click();
  });
  await page.locator("#sidebar-file-tree-root").waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
}

async function createPage(page) {
  const previousPathname = new URL(page.url()).pathname;
  await page.getByRole("button", { name: "新建页面" }).click({ timeout: UI_TIMEOUT_MS });
  await page.waitForURL((url) => url.pathname.startsWith("/documents/") && url.pathname !== previousPathname, { timeout: UI_TIMEOUT_MS });
  const documentId = new URL(page.url()).pathname.split("/").filter(Boolean).pop();
  assert(documentId, "新建后 URL 缺少 documentId");
  await page.waitForFunction(
    (id) => Boolean(document.querySelector(`#sidebar-file-tree-root .tree-row[data-row-id="doc:${CSS.escape(id)}"]`)),
    documentId,
    { timeout: UI_TIMEOUT_MS },
  );
  return documentId;
}

async function beginRename(page, documentId) {
  const selector = `#sidebar-file-tree-root .tree-row[data-row-id="doc:${cssString(documentId)}"]`;
  await page.waitForFunction(
    (id) => Boolean(document.querySelector(`#sidebar-file-tree-root .tree-row[data-row-id="doc:${CSS.escape(id)}"]`)),
    documentId,
    { timeout: UI_TIMEOUT_MS },
  );
  const row = page.locator(selector).first();
  await row.scrollIntoViewIfNeeded({ timeout: UI_TIMEOUT_MS }).catch(async () => {
    await page.waitForTimeout(100);
    await page.locator(selector).first().scrollIntoViewIfNeeded({ timeout: UI_TIMEOUT_MS });
  });
  await row.click({ timeout: UI_TIMEOUT_MS }).catch(async () => {
    await page.waitForTimeout(100);
    await page.locator(selector).first().click({ timeout: UI_TIMEOUT_MS });
  });
  await page.keyboard.press("F2");
  const input = page.locator(`${selector} .tree-rename-input`).first();
  await input.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  return input;
}

async function readRenameState(page, documentId) {
  return page.evaluate((id) => {
    const fileRow = document.querySelector(`#sidebar-file-tree-root .tree-row[data-row-id="doc:${CSS.escape(id)}"]`);
    const pageRow = document.querySelector(`#sidebar-tree-root .tree-row[data-node-id="${CSS.escape(id)}"]`);
    const validation = document.querySelector('[data-testid="tree-rename-validation"], [data-mnote-rename-validation]');
    return {
      documentTitle: document.title,
      fileTreeTitle: fileRow instanceof HTMLElement ? fileRow.querySelector(".tree-link-title")?.textContent?.trim() || "" : "",
      pageTreeTitle: pageRow instanceof HTMLElement ? pageRow.querySelector(".tree-link-title")?.textContent?.trim() || "" : "",
      validationText: validation instanceof HTMLElement ? validation.textContent?.trim() || "" : "",
      localApplied: document.documentElement.getAttribute("data-mnote-tree-local-command-applied") || "",
      activeFileRowSelected: fileRow instanceof HTMLElement ? fileRow.getAttribute("data-selected") || "" : "",
    };
  }, documentId);
}

async function main() {
  await fs.mkdir(OUT_DIR, { recursive: true });
  const browser = await chromium.launch({ headless: process.env.HEADFUL !== "1" });
  const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
  const page = await context.newPage();
  const requests = [];
  page.on("request", (request) => {
    if (request.url().includes("/api/tree/commands")) {
      requests.push({ url: request.url(), postData: request.postData() || "" });
    }
  });

  const result = { ok: false, baseUrl: BASE_URL, documentId: null, targetTitle: null, afterRename: null, invalidState: null, duplicateState: null, requests };

  try {
    await quickLogin(page);
    await page.goto(BASE_URL, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await openFileTree(page);
    const documentId = await createPage(page);
    result.documentId = documentId;
    await openFileTree(page);

    const targetTitle = `P2-Rename-${Date.now().toString().slice(-6)}`;
    result.targetTitle = targetTitle;
    let input = await beginRename(page, documentId);
    await input.fill(`${targetTitle}.md`);
    await input.press("Enter");
    await page.waitForFunction(
      ({ id, expected }) => {
        const fileRow = document.querySelector(`#sidebar-file-tree-root .tree-row[data-row-id="doc:${CSS.escape(id)}"]`);
        const pageRow = document.querySelector(`#sidebar-tree-root .tree-row[data-node-id="${CSS.escape(id)}"]`);
        const fileTitle = fileRow instanceof HTMLElement ? fileRow.querySelector(".tree-link-title")?.textContent?.trim() || "" : "";
        const pageTitle = pageRow instanceof HTMLElement ? pageRow.querySelector(".tree-link-title")?.textContent?.trim() || "" : "";
        return fileTitle === `${expected}.md` && pageTitle === expected;
      },
      { id: documentId, expected: targetTitle },
      { timeout: UI_TIMEOUT_MS },
    );
    result.afterRename = await readRenameState(page, documentId);
    assert.equal(result.afterRename.fileTreeTitle, `${targetTitle}.md`, "File Tree 应显示 .md 文件名");
    assert.equal(result.afterRename.pageTreeTitle, targetTitle, "Page Tree 标题不应带 .md");

    input = await beginRename(page, documentId);
    await input.fill("非法/名称.md");
    await input.press("Enter");
    result.invalidState = await readRenameState(page, documentId);
    assert.match(result.invalidState.validationText, /不能包含|非法/, "非法文件名应显示结构化校验提示");

    await page.keyboard.press("Escape").catch(() => {});
    const duplicateDocumentId = await createPage(page);
    await openFileTree(page);
    const renameRequestCountBeforeDuplicate = requests.filter((entry) => {
      try {
        const body = JSON.parse(entry.postData || "{}");
        return body.action === "rename";
      } catch (_) {
        return false;
      }
    }).length;
    input = await beginRename(page, duplicateDocumentId);
    await input.fill(`${targetTitle}.md`);
    await input.press("Enter");
    result.duplicateState = await readRenameState(page, duplicateDocumentId);
    assert.match(result.duplicateState.validationText, /同级已存在/, "同级重名应显示结构化校验提示");
    const renameRequestCountAfterDuplicate = requests.filter((entry) => {
      try {
        const body = JSON.parse(entry.postData || "{}");
        return body.action === "rename";
      } catch (_) {
        return false;
      }
    }).length;
    assert.equal(renameRequestCountAfterDuplicate, renameRequestCountBeforeDuplicate, "同级重名不应提交 rename command");

    result.ok = true;
  } finally {
    await fs.writeFile(path.join(OUT_DIR, "result.json"), `${JSON.stringify(result, null, 2)}\n`, "utf8");
    await browser.close().catch(() => {});
  }

  console.log(JSON.stringify(result, null, 2));
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
