import "server-only";
import fs from "fs/promises";
import path from "path";
import type { LearnVariant } from "@/lib/content/gua-utils";

export type { LearnVariant } from "@/lib/content/gua-utils";
export {
  extractChangeDetails,
  extractZhangMingRen,
  getGuaName,
  getGuaNumber,
  guaNumFromMark,
  stripFrontmatter,
} from "@/lib/content/gua-utils";

const DOCS_ROOT = path.join(process.cwd(), "content", "zhouyi", "docs");
const OTHER_ROOT = path.join(DOCS_ROOT, "other");

function getVariantRoot(variant: LearnVariant): string {
  return variant === "traditional" ? DOCS_ROOT : OTHER_ROOT;
}

export async function listGuaMarks(
  variant: LearnVariant = "traditional",
): Promise<string[]> {
  const dir = getVariantRoot(variant);
  const entries = await fs.readdir(dir, { withFileTypes: true });
  return entries
    .filter((entry) => entry.isDirectory() && /^\d{2}\./.test(entry.name))
    .map((entry) => entry.name)
    .sort();
}

/** 由序号解析目录名，如 "35" → "35.火地晋" */
export async function markFromNum(
  num: string,
  variant: LearnVariant = "traditional",
): Promise<string | null> {
  const padded = num.padStart(2, "0").slice(-2);
  const marks = await listGuaMarks(variant);
  return marks.find((m) => m.startsWith(`${padded}.`)) ?? null;
}

export async function readGuaMarkdown(guaMark: string): Promise<string> {
  const filePath = path.join(DOCS_ROOT, guaMark, "index.md");
  return fs.readFile(filePath, "utf-8");
}

export async function readLearnMarkdown(
  guaMark: string,
  variant: LearnVariant = "traditional",
): Promise<string> {
  const root = getVariantRoot(variant);
  const filePath =
    guaMark === "index"
      ? path.join(root, "index.md")
      : path.join(root, guaMark, "index.md");
  return fs.readFile(filePath, "utf-8");
}
