/**
 * SET 45a metrics strip + SET 45c substrate-page efficacy (34d pattern).
 */
import { describe, expect, it } from 'vitest';
import {
  emptyStatsTotals,
  emptySubstratePageEfficacy,
  formatSubstratePageEfficacy,
  formatSubstratePageEfficacyReportLine,
  formatSubstrateStrip,
  noteSubstratePageEfficacy,
  runSnapshot,
  contributeRunToTotals,
  type RunRecordLike,
} from '../src/tier1/statsAggregate';

describe('SET 45a substrate strip', () => {
  it('formats metrics-card strip', () => {
    expect(formatSubstrateStrip({
      actions: 12,
      fixes: 4,
      attempts: 10,
      refusals: 3,
      candidates: 5,
    })).toBe('substrate: 12 actions (4 fixes · 10 attempts · 3 refusals · 5 candidates)');
  });
});

describe('SET 45c substrate page efficacy', () => {
  it('formats WITH vs WITHOUT substrate page report line', () => {
    const line = formatSubstratePageEfficacy(
      { cases: 8, filled: 6 },
      { cases: 4, filled: 1 },
    );
    expect(line).toBe(
      'substrate page: 8 cases, 6 filled (75%) · no substrate page: 4 cases, 1 filled (25%)',
    );
    expect(formatSubstratePageEfficacyReportLine(
      { cases: 8, filled: 6 },
      { cases: 4, filled: 1 },
    )).toBe(line);
  });

  it('noteSubstratePageEfficacy accumulates buckets', () => {
    const buckets = emptySubstratePageEfficacy();
    noteSubstratePageEfficacy(buckets, true, true);
    noteSubstratePageEfficacy(buckets, true, false);
    noteSubstratePageEfficacy(buckets, false, true);
    expect(buckets.withPage).toEqual({ cases: 2, filled: 1 });
    expect(buckets.withoutPage).toEqual({ cases: 1, filled: 1 });
  });

  it('aggregates substrate page efficacy metrics fields', () => {
    const rec: RunRecordLike = {
      id: 'r1',
      ts: '2026-07-26T12:00:00.000Z',
      mode: 'rha',
      problems: 0,
      metrics: {
        substratePageWithCases: 8,
        substratePageWithFilled: 6,
        substratePageWithoutCases: 4,
        substratePageWithoutFilled: 1,
      },
    };
    const snap = runSnapshot(rec);
    expect(snap.substratePageWithCases).toBe(8);
    expect(snap.substratePageWithFilled).toBe(6);
    expect(snap.substratePageWithoutCases).toBe(4);
    expect(snap.substratePageWithoutFilled).toBe(1);

    const totals = emptyStatsTotals();
    contributeRunToTotals(totals, rec);
    expect(totals.substrate.pageWithCases).toBe(8);
    expect(totals.substrate.pageWithFilled).toBe(6);
    expect(totals.substrate.pageWithoutCases).toBe(4);
    expect(totals.substrate.pageWithoutFilled).toBe(1);
  });
});
