// src/lib/keywords/seasonal.ts — "peak approaching" detection from the monthly series.
import type { MonthlyVolume } from "./types";

export type SeasonalSuggestion = { peakMonth: number; monthsUntil: number };

const MIN_POINTS = 6;
const PEAK_RATIO = 1.5; // peak month avg must exceed 1.5× the overall mean
const WINDOW = 4; // suggest only when the peak is 1..4 months ahead

/** From a monthly volume series, if there's a clear seasonal peak whose next
 *  occurrence is within {WINDOW} months of `now`, return it; otherwise null. */
export function seasonalSuggestion(
  trend: MonthlyVolume[],
  now: Date,
): SeasonalSuggestion | null {
  if (!trend || trend.length < MIN_POINTS) return null;
  const sum = new Array(13).fill(0);
  const cnt = new Array(13).fill(0);
  let total = 0;
  for (const p of trend) {
    const m = Number(p.month.slice(5, 7));
    if (m < 1 || m > 12) continue;
    sum[m] += p.volume;
    cnt[m] += 1;
    total += p.volume;
  }
  const mean = total / trend.length;
  if (mean <= 0) return null;
  let peakMonth = 0;
  let peakAvg = -1;
  for (let m = 1; m <= 12; m++) {
    if (cnt[m] === 0) continue;
    const avg = sum[m] / cnt[m];
    if (avg > peakAvg) {
      peakAvg = avg;
      peakMonth = m;
    }
  }
  if (peakMonth === 0 || peakAvg < mean * PEAK_RATIO) return null;
  const cur = now.getMonth() + 1; // 1..12
  let monthsUntil = peakMonth - cur;
  if (monthsUntil <= 0) monthsUntil += 12;
  if (monthsUntil < 1 || monthsUntil > WINDOW) return null;
  return { peakMonth, monthsUntil };
}
