import type { ReportSynthesis } from '../types';

/** Count how many trend charts a report has (quarterly rating, domain sentiment, seasonal). */
export function countTrendsCharts(report: ReportSynthesis): number {
  let n = 0;
  if ((report.charts?.quarterly_rating?.length ?? 0) > 1) n++;
  if ((report.charts?.quarterly_domain_sentiment?.length ?? 0) > 1) n++;
  if ((report.charts?.seasonal_pattern?.length ?? 0) > 1) n++;
  return n;
}

/** Count pages needed for the trends section, accounting for AI narrative. */
export function countTrendsPages(report: ReportSynthesis): number {
  const chartCount = countTrendsCharts(report);
  if (chartCount === 0) return 0;
  const hasNarrative = !!report.trends_narrative;
  // With narrative: 1 chart on first page, 2 on continuation
  // Without narrative: 2 charts on first page, 3 on continuation
  return countPages(chartCount, hasNarrative ? 1 : 2, hasNarrative ? 2 : 3);
}

export function paginateItems<T>(items: T[], firstPageLimit: number, nextPageLimit: number): T[][] {
  if (items.length <= firstPageLimit) return [items];
  const pages: T[][] = [items.slice(0, firstPageLimit)];
  let offset = firstPageLimit;
  while (offset < items.length) {
    pages.push(items.slice(offset, offset + nextPageLimit));
    offset += nextPageLimit;
  }
  return pages;
}

export function countPages(itemCount: number, firstPageLimit: number, nextPageLimit: number): number {
  if (itemCount === 0) return 0;
  if (itemCount <= firstPageLimit) return 1;
  return 1 + Math.ceil((itemCount - firstPageLimit) / nextPageLimit);
}
