import "server-only";

import path from "node:path";
import { promises as fs } from "node:fs";
import { getDocumentsBaseDir } from "@/lib/server/local-paths";

const documentsBaseDir = getDocumentsBaseDir();

export async function ensureDocumentScaffold(id: string, title: string | null) {
  const folder = path.join(documentsBaseDir, id);
  const indexFile = path.join(folder, "index.md");
  await fs.mkdir(folder, { recursive: true });

  try {
    await fs.access(indexFile);
  } catch {
    const safeTitle = title && title.trim() ? title.trim() : "无标题";
    await fs.writeFile(indexFile, `# ${safeTitle}\n`, "utf8");
  }
}

export async function copyMindmapFilesIfExists(sourceId: string, targetId: string) {
  const srcDir = path.join(documentsBaseDir, sourceId);
  const destDir = path.join(documentsBaseDir, targetId);

  try {
    const entries = await fs.readdir(srcDir);
    const mindmapFiles = entries.filter(
      (name) => name === "mindmap.json" || /^mindmap-.+\.json$/i.test(name),
    );
    if (mindmapFiles.length === 0) return;

    await fs.mkdir(destDir, { recursive: true });
    await Promise.all(
      mindmapFiles.map(async (name) => {
        try {
          const sourceFile = path.join(srcDir, name);
          const targetFile = path.join(destDir, name);
          const buffer = await fs.readFile(sourceFile);
          await fs.writeFile(targetFile, buffer);
        } catch {
          // 说明：本地思维导图副作用失败不应反向打断主页面操作。
        }
      }),
    );
  } catch {
    // 说明：源页面不存在本地思维导图文件时直接忽略。
  }
}
