import { HolidayUtil, Solar } from 'lunar-javascript';

export interface DayLunarInfo {
  /** 单元格副标题：节日名或农历日 */
  label: string;
  /** 完整农历，如 四月廿七 */
  fullLunar: string;
  /** 节日/节气高亮 */
  isHighlight: boolean;
  /** 节日或节气名称 */
  festival?: string;
}

const cache = new Map<string, DayLunarInfo>();

const pickSolarFestival = (festivals: string[]) => festivals.find((name) => !/^国际/.test(name));

const resolveFestival = (dateStr: string, solar: Solar, lunar: ReturnType<Solar['getLunar']>) => {
  const holiday = HolidayUtil.getHoliday(dateStr);
  if (holiday) return holiday.getName();

  const lunarFestivals = lunar.getFestivals();
  if (lunarFestivals.length) return lunarFestivals[0];

  const solarFestival = pickSolarFestival(solar.getFestivals());
  if (solarFestival) return solarFestival;

  const jieQi = lunar.getJieQi();
  if (jieQi) return jieQi;

  return '';
};

export const getDayLunarInfo = (dateStr: string): DayLunarInfo => {
  const cached = cache.get(dateStr);
  if (cached) return cached;

  const [year, month, day] = dateStr.split('-').map(Number);
  const solar = Solar.fromYmd(year, month, day);
  const lunar = solar.getLunar();
  const festival = resolveFestival(dateStr, solar, lunar);

  let label = '';
  if (festival) {
    label = festival;
  } else if (lunar.getDay() === 1) {
    label = `${lunar.getMonthInChinese()}月`;
  } else {
    label = lunar.getDayInChinese();
  }

  const info: DayLunarInfo = {
    label,
    fullLunar: `${lunar.getMonthInChinese()}月${lunar.getDayInChinese()}`,
    isHighlight: !!festival,
    festival: festival || undefined
  };

  cache.set(dateStr, info);
  return info;
};
