import guaIndexData from "@/lib/data/gua-index.json";
import guaListData from "@/lib/data/gua-list.json";
import type { HexagramObj } from "@/components/hexagram";
import type { ResultObj } from "@/components/result";

const GUA_DICT1 = ["坤", "震", "坎", "兑", "艮", "离", "巽", "乾"];
const GUA_DICT2 = ["地", "雷", "水", "泽", "山", "火", "风", "天"];
const CHANGE_YANG = ["初九", "九二", "九三", "九四", "九五", "上九"];
const CHANGE_YIN = ["初六", "六二", "六三", "六四", "六五", "上六"];

/** 三钱法：正面数 0~3 → 爻象 */
export function frontCountToLine(frontCount: number): Omit<HexagramObj, "separate"> {
  return {
    change: frontCount === 0 || frontCount === 3,
    yang: frontCount >= 2,
  };
}

export function buildHexagramList(frontCounts: number[]): HexagramObj[] {
  return frontCounts.map((count, index) => ({
    ...frontCountToLine(count),
    separate: index === 3,
  }));
}

export function computeGuaResult(list: HexagramObj[]): ResultObj | null {
  if (list.length !== 6) {
    return null;
  }

  const changeList: string[] = [];
  list.forEach((value, index) => {
    if (!value.change) {
      return;
    }
    changeList.push(value.yang ? CHANGE_YANG[index] : CHANGE_YIN[index]);
  });

  const upIndex =
    (list[5].yang ? 4 : 0) + (list[4].yang ? 2 : 0) + (list[3].yang ? 1 : 0);
  const downIndex =
    (list[2].yang ? 4 : 0) + (list[1].yang ? 2 : 0) + (list[0].yang ? 1 : 0);

  const guaIndex = guaIndexData[upIndex][downIndex] - 1;
  const guaName1 = guaListData[guaIndex];

  let guaName2: string;
  if (upIndex === downIndex) {
    guaName2 = GUA_DICT1[upIndex] + "为" + GUA_DICT2[upIndex];
  } else {
    guaName2 = GUA_DICT2[upIndex] + GUA_DICT2[downIndex] + guaName1;
  }

  const guaDesc = GUA_DICT1[upIndex] + "上" + GUA_DICT1[downIndex] + "下";

  return {
    guaMark: `${(guaIndex + 1).toString().padStart(2, "0")}.${guaName2}`,
    guaTitle: `周易第${guaIndex + 1}卦`,
    guaResult: `${guaName1}卦(${guaName2})_${guaDesc}`,
    guaChange:
      changeList.length === 0 ? "无变爻" : `变爻: ${changeList.toString()}`,
  };
}

export const YAO_LABELS = ["初爻", "二爻", "三爻", "四爻", "五爻", "上爻"];

export const COIN_OPTIONS = [
  { count: 0, label: "老阴", desc: "0 正 · 变爻 ✕" },
  { count: 1, label: "少阴", desc: "1 正" },
  { count: 2, label: "少阳", desc: "2 正" },
  { count: 3, label: "老阳", desc: "3 正 · 变爻 ○" },
];

export interface GuaResult {
  list: HexagramObj[];
  result: ResultObj;
}
