import { describe, it, expect } from 'vitest';
import { renderReportMarkdown, isReportDue, type ReportStats } from '../reports.js';

function makeStats(partial: Partial<ReportStats> = {}): ReportStats {
  return {
    periodStart: '2026-06-11T00:00:00.000Z',
    periodEnd: '2026-06-12T00:00:00.000Z',
    interval: 'daily',
    totalRequests: 100,
    priorRequests: 50,
    totalInputTokens: 1000,
    totalOutputTokens: 2000,
    bySource: [{ source: 'boochat', requests: 80, inputTokens: 800, outputTokens: 1600 }],
    byProvider: [{ providerId: 'sam-desktop', requests: 100, swaps: 4 }],
    leaderboard: [{ providerId: 'sam-desktop', model: 'qwopus-35b', kind: 'code', avgScore: 0.82 }],
    regressions: [],
    ...partial,
  };
}

describe('renderReportMarkdown', () => {
  it('renders usage with a trend vs the prior period', () => {
    const md = renderReportMarkdown(makeStats());
    expect(md).toContain('# Fleet daily report');
    expect(md).toContain('Requests: 100 (+100% vs prior period)');
    expect(md).toContain('| boochat | 80 |');
    expect(md).toContain('| sam-desktop | 100 | 4 |');
    expect(md).toContain('No speed regressions flagged this period.');
  });

  it('renders regression anomalies when present', () => {
    const md = renderReportMarkdown(makeStats({
      regressions: [{ providerId: 'sam-desktop', model: 'qwopus-35b', avgGenTps: 42.5 }],
    }));
    expect(md).toContain('Regression: sam-desktop/qwopus-35b');
    expect(md).toContain('42.5 tok/s');
  });

  it('handles a zero prior period without dividing by zero', () => {
    const md = renderReportMarkdown(makeStats({ totalRequests: 5, priorRequests: 0 }));
    expect(md).toContain('Requests: 5 (new vs prior period)');
  });
});

describe('isReportDue', () => {
  const now = new Date('2026-06-12T12:00:00.000Z');

  it('is due when never run', () => {
    expect(isReportDue(null, 'daily', now)).toBe(true);
  });

  it('is not due within the interval', () => {
    const lastRun = new Date('2026-06-12T06:00:00.000Z'); // 6h ago
    expect(isReportDue(lastRun, 'daily', now)).toBe(false);
  });

  it('is due once the interval has elapsed', () => {
    const lastRun = new Date('2026-06-11T06:00:00.000Z'); // 30h ago
    expect(isReportDue(lastRun, 'daily', now)).toBe(true);
  });

  it('uses a 7-day window for weekly', () => {
    const lastRun = new Date('2026-06-09T12:00:00.000Z'); // 3 days ago
    expect(isReportDue(lastRun, 'weekly', now)).toBe(false);
  });
});
