"use strict";

const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");

const BASE_URL = (process.env.MNOTE_WEB_SMOKE_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
const OUTPUT_DIR = path.join(process.cwd(), "tmp", "task437-local-folder-asset-trash-lifecycle-smoke");
const RESULT_PATH = path.join(OUTPUT_DIR, "result.json");

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:task437",
      ownerId: "user_real",
      createdAt: new Date().toISOString(),
      capabilities: ["local_files", "tree_commands", "markdown_edit", "asset_upload"],
    }, null, 2)}\n`,
    "utf8",
  );
}

async function postTreeCommand(payload) {
  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(payload),
  });
  const json = await response.json().catch(async () => ({ text: await response.text() }));
  assert.equal(response.status, 200, `${payload.action} failed: ${JSON.stringify(json)}`);
  return json;
}

async function runStep(label, action) {
  const detail = await action();
  return { label, detail: detail || null };
}

async function run() {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-local-asset-trash-smoke-"));
  fs.mkdirSync(path.join(root, "docs"), { recursive: true });
  writeWorkspaceManifest(root);
  fs.writeFileSync(path.join(root, "README.md"), "# Local Root\n", "utf8");
  fs.writeFileSync(path.join(root, "docs", "asset.txt"), "asset body", "utf8");

  const rootUri = fileUrl(root);
  const assetId = "local-file:docs/asset.txt";
  const sourcePath = path.join(root, "docs", "asset.txt");
  const trashPath = path.join(root, ".mnote", "trash", "asset.txt");
  const trashIndexPath = path.join(root, ".mnote", "trash-index.json");
  const steps = [];
  try {
    steps.push(await runStep("local-file delete 进入本地回收站", async () => {
      const result = await postTreeCommand({
        action: "delete",
        sourceKind: "local_folder",
        rootUri,
        documentId: assetId,
      });
      assert.equal(result.result?.execution?.canonicalCommand, "tree.resource.archive");
      assert.equal(fs.existsSync(sourcePath), false, "Delete 后源文件应消失");
      assert.equal(fs.existsSync(trashPath), true, "Delete 后文件应进入 .mnote/trash");
      const index = fs.readFileSync(trashIndexPath, "utf8");
      assert.match(index, /local-file:docs\/asset\.txt/, "trash index 应记录 local-file entry");
      return result.result?.execution || null;
    }));

    steps.push(await runStep("local-file restore 回原路径", async () => {
      const result = await postTreeCommand({
        action: "restore",
        sourceKind: "local_folder",
        rootUri,
        documentId: assetId,
      });
      assert.equal(result.result?.execution?.canonicalCommand, "tree.resource.restore");
      assert.equal(fs.existsSync(sourcePath), true, "restore 后源文件应恢复");
      return result.result?.execution || null;
    }));

    steps.push(await runStep("local-file purge 清理 trash 文件与索引", async () => {
      await postTreeCommand({
        action: "delete",
        sourceKind: "local_folder",
        rootUri,
        documentId: assetId,
      });
      const result = await postTreeCommand({
        action: "purge",
        sourceKind: "local_folder",
        rootUri,
        documentId: assetId,
      });
      assert.equal(result.result?.execution?.canonicalCommand, "tree.resource.purge");
      assert.equal(fs.existsSync(sourcePath), false, "purge 后源文件不应存在");
      assert.equal(fs.existsSync(trashPath), false, "purge 后 trash 文件不应存在");
      const index = fs.readFileSync(trashIndexPath, "utf8");
      assert.doesNotMatch(index, /local-file:docs\/asset\.txt/, "purge 后 trash index 应清理 entry");
      return result.result?.execution || null;
    }));

    const result = {
      ok: true,
      baseUrl: BASE_URL,
      root,
      assetId,
      steps,
    };
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify(result, null, 2)}\n`, "utf8");
    console.log(`task437 local folder asset trash lifecycle smoke passed: ${RESULT_PATH}`);
  } finally {
    fs.rmSync(root, { recursive: true, force: true });
  }
}

run().catch((error) => {
  const result = {
    ok: false,
    baseUrl: BASE_URL,
    error: error && error.stack ? error.stack : String(error),
  };
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  fs.writeFileSync(RESULT_PATH, `${JSON.stringify(result, null, 2)}\n`, "utf8");
  console.error(error && error.stack ? error.stack : error);
  process.exit(1);
});
