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

const assert = require("node:assert");
const fs = require("node:fs");
const fsp = 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", "task441-local-folder-cloud-switch-smoke");
const MANAGED_MY_SPACE_ROOT = "/mnt/Data1T/Mnote_data/users/mnote-e2e/workspaces/my-space";

function fileUrl(filePath) {
  return `file://${filePath.split(path.sep).map((part, index) => (index === 0 ? "" : encodeURIComponent(part))).join("/")}`;
}

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 readCloudState(page) {
  return page.evaluate(() => {
    const workspaceNode = document.querySelector("#sidebar-file-tree-root[data-workspace-id], #sidebar-tree-root[data-workspace-id], [data-workspace-id]");
    const workspaceId = workspaceNode instanceof HTMLElement ? workspaceNode.getAttribute("data-workspace-id") || "" : "";
    const url = new URL(window.location.href);
    const sourceKind = document.body?.getAttribute("data-mnote-source-kind") || url.searchParams.get("sourceKind") || "";
    const rootUri = document.body?.getAttribute("data-mnote-root-uri") || url.searchParams.get("rootUri") || "";
    const docRows = Array.from(document.querySelectorAll("#sidebar-file-tree-root .tree-row[data-row-id^='doc:']")).map((row) => ({
      rowId: row.getAttribute("data-row-id") || "",
      title: row.querySelector(".tree-link-title")?.textContent?.trim() || "",
    }));
    return {
      url: window.location.href,
      sourceKind,
      rootUri,
      workspaceId,
      storageValue: window.localStorage.getItem("mnote.workspace.lastCloudWorkspaceId") || "",
      docRows,
      localMarkdownRows: Array.from(document.querySelectorAll("#sidebar-file-tree-root .tree-row[data-row-id^='local:markdown:']")).map((row) => ({
        rowId: row.getAttribute("data-row-id") || "",
        title: row.querySelector(".tree-link-title")?.textContent?.trim() || "",
      })),
      localRows: document.querySelectorAll("#sidebar-file-tree-root .tree-row[data-row-id^='local:']").length,
      rootText: document.querySelector("#sidebar-file-tree-root")?.textContent?.slice(0, 500) || "",
    };
  });
}

function isHomeWorkspaceState(state) {
  return state.sourceKind === "local_folder" && state.workspaceId.startsWith("local-ws:");
}

async function ensureHomeWorkspace(page) {
  await openFileTree(page);
  let state = await readCloudState(page);
  if (isHomeWorkspaceState(state)) return state;

  await switchCloud(page);
  await openFileTree(page);
  state = await readCloudState(page);
  assert(isHomeWorkspaceState(state), `切回我的空间后应进入默认本地 workspace: ${JSON.stringify(state)}`);
  return state;
}

async function ensureHomeWorkspaceTarget(page) {
  const state = await ensureHomeWorkspace(page);
  return {
    workspaceId: state.workspaceId,
    rootUri: state.rootUri,
    rowId: state.localMarkdownRows[0]?.rowId || "",
  };
}

async function openLocalFolder(page, root) {
  await page.locator('[data-testid="mnote-workspace-source-trigger"]').click({ timeout: UI_TIMEOUT_MS });
  await page.locator('[data-testid="mnote-workspace-source-menu"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await page.locator('[data-testid="mnote-open-other-local-folder"]').click({ timeout: UI_TIMEOUT_MS });
  await page.locator('[data-testid="mnote-local-folder-dialog"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await page.locator('[data-testid="mnote-local-folder-path-input"]').fill(root);
  await page.locator('[data-testid="mnote-local-folder-open-confirm"]').click({ timeout: UI_TIMEOUT_MS });
  await page.waitForURL(
    (url) => url.pathname === "/" && url.searchParams.get("sourceKind") === "local_folder" && url.searchParams.get("rootUri") === fileUrl(root),
    { timeout: UI_TIMEOUT_MS },
  );
  await page.locator("#sidebar-file-tree-root .tree-row[data-row-id='local:markdown:README.md']").waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
}

async function switchCloud(page) {
  await page.locator('[data-testid="mnote-workspace-source-trigger"]').click({ timeout: UI_TIMEOUT_MS });
  await page.locator('[data-testid="mnote-workspace-source-menu"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await page.locator('[data-testid="mnote-switch-cloud-workspace"]').click({ timeout: UI_TIMEOUT_MS });
  await page.waitForURL(
    (url) => url.pathname === "/" && url.searchParams.get("mnoteHome") === "1" && !url.searchParams.has("sourceKind") && !url.searchParams.has("rootUri"),
    { timeout: UI_TIMEOUT_MS },
  );
}

async function main() {
  await fsp.mkdir(OUT_DIR, { recursive: true });
  fs.mkdirSync(MANAGED_MY_SPACE_ROOT, { recursive: true });
  let localRoot = "";

  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 result = { ok: false, baseUrl: BASE_URL, localRoot, homeTarget: null, localState: null, returnedState: null };

  try {
    await quickLogin(page);
    await page.goto(BASE_URL, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    result.homeTarget = await ensureHomeWorkspaceTarget(page);
    localRoot = fs.mkdtempSync(path.join(MANAGED_MY_SPACE_ROOT, "task441-local-"));
    result.localRoot = localRoot;
    fs.writeFileSync(path.join(localRoot, "README.md"), "# Local README\n", "utf8");
    await openLocalFolder(page, localRoot);
    result.localState = await readCloudState(page);
    assert(
      !result.localState.storageValue || !result.localState.storageValue.startsWith("local-ws:"),
      `进入普通本地文件夹不应把我的空间 local-ws 写成云 workspace: ${JSON.stringify(result)}`,
    );

    await switchCloud(page);
    await openFileTree(page);
    result.returnedState = await readCloudState(page);

    assert.equal(result.returnedState.workspaceId, result.homeTarget.workspaceId, "切回我的空间后应恢复默认本地 workspaceId");
    assert.equal(result.returnedState.sourceKind, "local_folder", "切回我的空间后仍应走 local_folder 主链");
    assert.equal(result.returnedState.rootUri, result.homeTarget.rootUri, "切回我的空间后应恢复默认 my-space rootUri");
    assert.notEqual(result.returnedState.rootUri, fileUrl(localRoot), "切回我的空间后不能继续停留在刚打开的普通本地文件夹");
    assert.notEqual(result.returnedState.storageValue, "default", "lastCloudWorkspaceId 不能是 synthetic default");
    assert(!result.returnedState.storageValue.startsWith("local-ws:"), "lastCloudWorkspaceId 不能是 local-ws:*");
    assert(result.returnedState.localRows > 0, `切回我的空间后 File Tree 应恢复本地 row: ${JSON.stringify(result.returnedState)}`);

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

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

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