/** 客户端/服务端均可用的卦名工具（不含 fs） */

export type LearnVariant = "traditional" | "simplified";

export function guaNumFromMark(guaMark: string): string {
  return guaMark.split(".")[0];
}

export function getGuaNumber(guaMark: string): number {
  return parseInt(guaMark.split(".")[0], 10);
}

export function getGuaName(guaMark: string): string {
  return guaMark.split(".").slice(1).join(".");
}

export function stripFrontmatter(content: string): string {
  if (!content.startsWith("---")) {
    return content;
  }
  const end = content.indexOf("---", 3);
  if (end === -1) {
    return content;
  }
  return content.slice(end + 3).trimStart();
}

export function extractZhangMingRen(guaDetail: string): string | undefined {
  return guaDetail
    .match(/(\*\*台灣張銘仁[\s\S]*?)(?=周易第\d+卦)/)?.[1]
    ?.replaceAll("\n\n", "\n");
}

export function extractChangeDetails(
  guaDetail: string,
  guaChange: string,
  guaTitle: string,
): string[] {
  const changeList: string[] = [];
  if (guaChange === "无变爻") {
    return changeList;
  }

  const changePart = guaChange.includes(":")
    ? guaChange.split(":").slice(1).join(":").trim()
    : guaChange.trim();
  if (!changePart) {
    return changeList;
  }

  changePart.split(",").forEach((change) => {
      const detail = guaDetail
        .match(`(\\*\\*${change}變卦[\\s\\S]*?)(?=${guaTitle}|$)`)?.[1]
        ?.replaceAll("\n\n", "\n");
      if (detail) {
        changeList.push(detail.trim());
      }
    });

  return changeList;
}
