import { Solar } from "lunar-javascript";
import {
  adjustToTrueSolarTime,
  formatDateTime,
  parseDateTime,
} from "@/lib/calc/time";

export interface TimingInfo {
  solarTime: string;
  lunarDate: string;
  yearGanZhi: string;
  monthGanZhi: string;
  dayGanZhi: string;
  timeGanZhi: string;
  prevJieQi: string;
  nextJieQi: string;
}

export function getTimingInfo(dateTime: Date): TimingInfo {
  const solar = Solar.fromYmdHms(
    dateTime.getFullYear(),
    dateTime.getMonth() + 1,
    dateTime.getDate(),
    dateTime.getHours(),
    dateTime.getMinutes(),
    0,
  );
  const lunar = solar.getLunar();

  return {
    solarTime: formatDateTime(dateTime),
    lunarDate: lunar.toString(),
    yearGanZhi: lunar.getYearInGanZhi(),
    monthGanZhi: lunar.getMonthInGanZhi(),
    dayGanZhi: lunar.getDayInGanZhi(),
    timeGanZhi: lunar.getTimeInGanZhi(),
    prevJieQi: lunar.getPrevJieQi()?.getName() ?? "—",
    nextJieQi: lunar.getNextJieQi()?.getName() ?? "—",
  };
}

export function getTimingInfoFromStrings(
  date: string,
  time: string,
): TimingInfo {
  return getTimingInfo(parseDateTime(date, time));
}

export function getTimingInfoWithLongitude(
  date: string,
  time: string,
  longitude: number,
): { timing: TimingInfo; trueSolarTime: string } {
  const local = parseDateTime(date, time);
  const trueSolar = adjustToTrueSolarTime(local, longitude);
  return {
    timing: getTimingInfo(trueSolar),
    trueSolarTime: formatDateTime(trueSolar),
  };
}

export function formatLiuyaoTimingForPrompt(
  timing: TimingInfo,
  trueSolarTime: string,
  locationName: string,
  longitude: number,
): string {
  return [
    "【起卦时空 · 天时】",
    `起卦时刻：${timing.solarTime}`,
    `真太阳时：${trueSolarTime}`,
    `农历：${timing.lunarDate}`,
    `年柱：${timing.yearGanZhi}，月柱：${timing.monthGanZhi}，日柱：${timing.dayGanZhi}，时柱：${timing.timeGanZhi}`,
    `节气：上一节气 ${timing.prevJieQi}，下一节气 ${timing.nextJieQi}`,
    "",
    "【起卦地域 · 地利】",
    `位置：${locationName}`,
    `经度：${longitude}°`,
  ].join("\n");
}

export function formatTimingForPrompt(
  timing: TimingInfo,
  locationName: string,
  longitude: number,
): string {
  return [
    "【天时】",
    `测算时刻：${timing.solarTime}`,
    `农历：${timing.lunarDate}`,
    `年柱：${timing.yearGanZhi}，月柱：${timing.monthGanZhi}，日柱：${timing.dayGanZhi}，时柱：${timing.timeGanZhi}`,
    `节气：上一节气 ${timing.prevJieQi}，下一节气 ${timing.nextJieQi}`,
    "",
    "【地利】",
    `当前位置：${locationName}`,
    `经度：${longitude}°`,
  ].join("\n");
}
