import "server-only";

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

export function resolveMindmapFileName(mindmapId: string) {
  if (mindmapId === "legacy" || mindmapId.startsWith("legacy-")) {
    return "mindmap.json";
  }
  return `mindmap-${mindmapId}.json`;
}

async function ensureDir(dir: string) {
  await fs.mkdir(dir, { recursive: true });
}

async function ensureIndexFile(folder: string, title = "无标题") {
  const indexFile = path.join(folder, "index.md");
  try {
    await fs.access(indexFile);
  } catch {
    await fs.writeFile(indexFile, `# ${title}\n`, "utf8");
  }
}

async function tryReadJson(file: string) {
  try {
    const content = await fs.readFile(file, "utf8");
    return JSON.parse(content);
  } catch {
    return null;
  }
}

export type ReadMindmapResult =
  | { ok: true; data: any; source: "preferred" | "legacy" }
  | { ok: false; data: null; source: null };

export async function readMindmapLocal(docId: string, mindmapId: string): Promise<ReadMindmapResult> {
  const preferredBaseDir = getDocumentsBaseDir();
  const legacyBaseDir = getLegacyMindmapsBaseDir();
  const preferredFolder = path.join(preferredBaseDir, docId);
  const preferredFile = path.join(preferredFolder, resolveMindmapFileName(mindmapId));
  const preferredLegacy = path.join(preferredFolder, "mindmap.json");
  const legacyDirFile =
    path.basename(preferredFile) === "mindmap.json"
      ? path.join(legacyBaseDir, docId, "mindmap.json")
      : null;

  const data =
    (await tryReadJson(preferredFile)) ??
    (await tryReadJson(preferredLegacy)) ??
    (legacyDirFile ? await tryReadJson(legacyDirFile) : null);

  if (data) return { ok: true, data, source: "preferred" };
  return { ok: false, data: null, source: null };
}

export async function writeMindmapLocal(
  docId: string,
  mindmapId: string,
  data: unknown,
  docTitle: string,
) {
  const folder = path.join(getDocumentsBaseDir(), docId);
  const file = path.join(folder, resolveMindmapFileName(mindmapId));
  await ensureDir(folder);
  await ensureIndexFile(folder, docTitle || "无标题");
  await fs.writeFile(file, JSON.stringify(data ?? { data: { text: "中心主题" }, children: [] }, null, 2), "utf8");
  return { folder, file };
}
