import { extractValue } from '../src/lib/dataExport';
import { listExportableParams } from '../src/lib/dataExport';

const status = {
  vitals: 'ok',
  custom_fields: { 'f-weight': 250 },
  analysis_summary: { total: 12, success_rate: 0.83, counts: { Success: 10, Failure: 2 } },
};

describe('extractValue', () => {
  it('reads a builtin field via statusKey', () => {
    expect(extractValue(status, { kind: 'builtin', statusKey: 'vitals' })).toBe('ok');
  });
  it('reads a custom field via fieldId', () => {
    expect(extractValue(status, { kind: 'custom', fieldId: 'f-weight' })).toBe(250);
  });
  it('reads session-metric total', () => {
    expect(extractValue(status, { kind: 'total' })).toBe(12);
  });
  it('reads session-metric success_rate as a raw 0-1 fraction', () => {
    expect(extractValue(status, { kind: 'success_rate' })).toBe(0.83);
  });
  it('reads a dynamic count category', () => {
    expect(extractValue(status, { kind: 'category', category: 'Failure' })).toBe(2);
  });
  it('returns null when analysis_summary is absent', () => {
    expect(extractValue({ custom_fields: {} }, { kind: 'total' })).toBeNull();
    expect(extractValue({}, { kind: 'category', category: 'Success' })).toBeNull();
  });
  it('returns null for a missing custom field', () => {
    expect(extractValue({ custom_fields: {} }, { kind: 'custom', fieldId: 'nope' })).toBeNull();
    expect(extractValue({}, { kind: 'builtin', statusKey: 'notes' })).toBeNull();
  });
});

const dailyTemplate = [
  { fieldId: 'b-vitals', key: 'vitals', label: 'Vitals', builtin: true, active: true },
  { fieldId: 'c-weight', key: 'weight', label: 'Weight (g)', builtin: false, active: false },
];
const statuses = [
  { analysis_summary: { counts: { Success: 1, Failure: 0 } } },
  { analysis_summary: { counts: { Success: 2, Other: 1 } } },
  { analysis_summary: null },
];

describe('listExportableParams', () => {
  const params = listExportableParams(dailyTemplate, statuses);
  it('starts with the two fixed session metrics', () => {
    expect(params.slice(0, 2)).toEqual([
      expect.objectContaining({ id: '__total__', label: 'Total attempts', group: 'metrics', kind: 'total' }),
      expect.objectContaining({ id: '__success_rate__', label: 'Success rate', group: 'metrics', kind: 'success_rate' }),
    ]);
  });
  it('adds one metrics entry per dynamic count category, sorted', () => {
    const cats = params.filter((p) => p.kind === 'category').map((p) => p.label);
    expect(cats).toEqual(['Failure', 'Other', 'Success']);
  });
  it('includes every template field (incl. inactive) in the daily group', () => {
    const daily = params.filter((p) => p.group === 'daily');
    expect(daily).toEqual([
      expect.objectContaining({ label: 'Vitals', kind: 'builtin', statusKey: 'vitals' }),
      expect.objectContaining({ label: 'Weight (g)', kind: 'custom', fieldId: 'c-weight' }),
    ]);
  });
  it('gives every param a unique id', () => {
    const ids = params.map((p) => p.id);
    expect(new Set(ids).size).toBe(ids.length);
  });
  it('tolerates empty/missing inputs', () => {
    expect(listExportableParams(undefined, undefined).length).toBe(2); // just the two fixed metrics
  });
});

import { toCSV, csvFilename } from '../src/lib/dataExport';

describe('toCSV', () => {
  it('emits context line, blank line, header, data (no group)', () => {
    const matrix = {
      corner: 'Date',
      context: { label: 'Parameter', value: 'Total attempts' },
      groupAxis: null,
      columns: [{ id: 'a1', label: 'Alpha', group: null }, { id: 'a2', label: 'Beta', group: null }],
      rows: [{ member: { label: '2026-07-01' }, values: [5, ''] }, { member: { label: '2026-07-02' }, values: ['', 9] }],
    };
    expect(toCSV(matrix)).toBe(
      'Parameter,Total attempts\n\nDate,Alpha,Beta\n2026-07-01,5,\n2026-07-02,,9',
    );
  });

  it('adds a Group header row when subjects are columns', () => {
    const matrix = {
      corner: 'Date',
      context: { label: 'Parameter', value: 'Total attempts' },
      groupAxis: 'col',
      columns: [{ id: 'a1', label: 'Alpha', group: 'Control' }, { id: 'a2', label: 'Beta', group: 'Drug' }],
      rows: [{ member: { label: '2026-07-01' }, values: [5, 9] }],
    };
    expect(toCSV(matrix)).toBe(
      'Parameter,Total attempts\n\nGroup,Control,Drug\nDate,Alpha,Beta\n2026-07-01,5,9',
    );
  });

  it('adds a leading Group column when subjects are rows', () => {
    const matrix = {
      corner: 'Subject',
      context: { label: 'Date', value: '2026-07-01' },
      groupAxis: 'row',
      columns: [{ id: 'p1', label: 'Total attempts', group: 'metrics' }],
      rows: [
        { member: { label: 'Alpha', group: 'Control' }, values: [5] },
        { member: { label: 'Beta', group: 'Drug' }, values: [9] },
      ],
    };
    expect(toCSV(matrix)).toBe(
      'Date,2026-07-01\n\nGroup,Subject,Total attempts\nControl,Alpha,5\nDrug,Beta,9',
    );
  });

  it('escapes commas, quotes, and newlines per RFC 4180', () => {
    const matrix = {
      corner: 'Date',
      context: { label: 'Parameter', value: 'Note, field' },
      groupAxis: null,
      columns: [{ id: 'a1', label: 'he said "hi"', group: null }],
      rows: [{ member: { label: '2026-07-01' }, values: ['line1\nline2'] }],
    };
    expect(toCSV(matrix)).toBe(
      'Parameter,"Note, field"\n\nDate,"he said ""hi"""\n2026-07-01,"line1\nline2"',
    );
  });
});

describe('csvFilename', () => {
  it('slugifies the experiment title and parameter label', () => {
    expect(csvFilename('My Study #1', 'Success rate')).toBe('My-Study-1-Success-rate.csv');
  });
  it('falls back to "export" when both slugs are empty', () => {
    expect(csvFilename('', '')).toBe('export.csv');
  });
});

import { subjectGroupValue } from '../src/lib/dataExport';

describe('subjectGroupValue', () => {
  const animal = { animal_name: 'Alpha', animal_id_string: 'R-001', subject_info: { sex: 'M', cohort: '' } };
  it('returns null when no group field', () => {
    expect(subjectGroupValue(animal, '__none__')).toBeNull();
    expect(subjectGroupValue(animal, '')).toBeNull();
  });
  it('resolves name / id / subject_info fields', () => {
    expect(subjectGroupValue(animal, '__name__')).toBe('Alpha');
    expect(subjectGroupValue(animal, '__id__')).toBe('R-001');
    expect(subjectGroupValue(animal, 'sex')).toBe('M');
  });
  it('renders missing or empty values as an em dash', () => {
    expect(subjectGroupValue(animal, 'cohort')).toBe('—');
    expect(subjectGroupValue({}, 'sex')).toBe('—');
  });
});

import { listSubjectMembers } from '../src/lib/dataExport';

describe('listSubjectMembers', () => {
  const animals = [
    { id: 'a2', animal_name: 'Beta', animal_id_string: 'R-002', subject_info: { grp: 'Drug' } },
    { id: 'a1', animal_name: 'Alpha', animal_id_string: 'R-001', subject_info: { grp: 'Control' } },
    { id: 'a3', animal_name: 'Gamma', animal_id_string: 'R-003', subject_info: { grp: 'Control' } },
  ];
  it('orders by name and carries group=null when no group field', () => {
    const m = listSubjectMembers(animals, '__none__');
    expect(m.map((s) => s.label)).toEqual(['Alpha', 'Beta', 'Gamma']);
    expect(m.every((s) => s.group === null)).toBe(true);
    expect(m[0]).toMatchObject({ id: 'a1', animalId: 'a1' });
  });
  it('clusters by group value then name when grouping is on', () => {
    const m = listSubjectMembers(animals, 'grp');
    expect(m.map((s) => [s.group, s.label])).toEqual([
      ['Control', 'Alpha'], ['Control', 'Gamma'], ['Drug', 'Beta'],
    ]);
  });
  it('disambiguates duplicate names with the id string', () => {
    const dup = [
      { id: 'a1', animal_name: 'Rat', animal_id_string: 'R-001' },
      { id: 'a2', animal_name: 'Rat', animal_id_string: 'R-002' },
    ];
    expect(listSubjectMembers(dup, '__none__').map((s) => s.label)).toEqual(['Rat (R-001)', 'Rat (R-002)']);
  });
});

import { numericFieldVal, listSampleMembers, buildSampleIndex } from '../src/lib/dataExport';

const sDaily = [{ fieldId: 'c-w', key: 'w', label: 'Weight', builtin: false, active: true }];
const sStatuses = [
  { animal_id: 'a1', date: '2026-07-01T00:00:00Z', custom_fields: { 'c-w': '250' } },
  { animal_id: 'a1', date: '2026-07-03T00:00:00Z', custom_fields: { 'c-w': '260' } },
  { animal_id: 'a2', date: '2026-07-01T00:00:00Z', custom_fields: { 'c-w': '250' } },
];

describe('numericFieldVal', () => {
  it('reads builtin via key and custom via fieldId, parsed to number', () => {
    expect(numericFieldVal({ weight: '250' }, { builtin: true, key: 'weight' })).toBe(250);
    expect(numericFieldVal({ custom_fields: { 'c-w': '12.5' } }, { builtin: false, fieldId: 'c-w' })).toBe(12.5);
  });
  it('returns null for non-numeric, missing, or no field', () => {
    expect(numericFieldVal({ custom_fields: { 'c-w': 'abc' } }, { builtin: false, fieldId: 'c-w' })).toBeNull();
    expect(numericFieldVal({}, { builtin: true, key: 'weight' })).toBeNull();
    expect(numericFieldVal({ weight: 1 }, null)).toBeNull();
  });
});

describe('listSampleMembers', () => {
  it('date: distinct dates sorted', () => {
    expect(listSampleMembers(sStatuses, '__date__', sDaily).map((m) => m.sampleValue)).toEqual(['2026-07-01', '2026-07-03']);
  });
  it('# days reach: 1..max records per subject', () => {
    expect(listSampleMembers(sStatuses, '__days__', sDaily).map((m) => m.sampleValue)).toEqual([1, 2]);
  });
  it('daily field: distinct numeric values sorted ascending', () => {
    expect(listSampleMembers(sStatuses, 'c-w', sDaily).map((m) => m.sampleValue)).toEqual([250, 260]);
  });
});

describe('buildSampleIndex', () => {
  it('date coord maps animalId -> dateKey -> status', () => {
    const idx = buildSampleIndex(sStatuses, '__date__', sDaily);
    expect(idx.get('a1').get('2026-07-03').date).toContain('2026-07-03');
  });
  it('# days reach assigns per-subject ordinals in date order', () => {
    const idx = buildSampleIndex(sStatuses, '__days__', sDaily);
    expect(idx.get('a1').get(1).date).toContain('2026-07-01');
    expect(idx.get('a1').get(2).date).toContain('2026-07-03');
    expect(idx.get('a2').get(1).date).toContain('2026-07-01');
    expect(idx.get('a2').has(2)).toBe(false);
  });
  it('daily field maps numeric value to first status by date', () => {
    const idx = buildSampleIndex(sStatuses, 'c-w', sDaily);
    expect(idx.get('a1').get(250).date).toContain('2026-07-01');
    expect(idx.get('a1').get(260).date).toContain('2026-07-03');
  });
  it('# days reach counts per-status, not per-distinct-date (same-day statuses get separate ordinals)', () => {
    const sameDay = [
      { animal_id: 'z1', date: '2026-07-01T08:00:00Z', analysis_summary: { total: 1 } },
      { animal_id: 'z1', date: '2026-07-01T20:00:00Z', analysis_summary: { total: 2 } },
    ];
    const idx = buildSampleIndex(sameDay, '__days__', []);
    expect(idx.get('z1').has(1)).toBe(true);
    expect(idx.get('z1').has(2)).toBe(true);
    expect(idx.get('z1').has(3)).toBe(false);
  });
});

import { buildSubjectSeriesMatrix } from '../src/lib/dataExport';

const ssAnimals = [
  { id: 'a1', animal_name: 'Alpha', animal_id_string: 'R-001', subject_info: { grp: 'Control' } },
  { id: 'a2', animal_name: 'Beta', animal_id_string: 'R-002', subject_info: { grp: 'Drug' } },
];
const ssStatuses = [
  { animal_id: 'a1', date: '2026-07-01T00:00:00Z', analysis_summary: { total: 5 } },
  { animal_id: 'a1', date: '2026-07-02T00:00:00Z', analysis_summary: { total: 7 } },
  { animal_id: 'a2', date: '2026-07-01T00:00:00Z', analysis_summary: { total: 9 } },
];
const totalParam = { id: '__total__', label: 'Total attempts', kind: 'total', group: 'metrics' };

describe('buildSubjectSeriesMatrix', () => {
  it('date X: subjects as columns, date rows, blank where missing, context names the metric', () => {
    const m = buildSubjectSeriesMatrix(
      { xField: '__date__', dataParam: totalParam, groupField: '__none__' },
      { statuses: ssStatuses, animals: ssAnimals, dailyTemplate: [] },
    );
    expect(m.corner).toBe('Date');
    expect(m.context).toEqual({ label: 'Data', value: 'Total attempts' });
    expect(m.groupAxis).toBeNull();
    expect(m.columns.map((c) => c.label)).toEqual(['Alpha', 'Beta']);
    expect(m.rows.map((r) => r.member.label)).toEqual(['2026-07-01', '2026-07-02']);
    expect(m.rows[0].values).toEqual([5, 9]);
    expect(m.rows[1].values).toEqual([7, '']);
  });
  it('# days reach X: rows align each subject by day ordinal', () => {
    const m = buildSubjectSeriesMatrix(
      { xField: '__days__', dataParam: totalParam, groupField: '__none__' },
      { statuses: ssStatuses, animals: ssAnimals, dailyTemplate: [] },
    );
    expect(m.corner).toBe('# Days Reach (ordinal)');
    expect(m.rows.map((r) => r.member.label)).toEqual(['1', '2']);
    expect(m.rows[0].values).toEqual([5, 9]);
    expect(m.rows[1].values).toEqual([7, '']);
  });
  it('grouping sets groupAxis col and clusters subjects', () => {
    const m = buildSubjectSeriesMatrix(
      { xField: '__date__', dataParam: totalParam, groupField: 'grp' },
      { statuses: ssStatuses, animals: ssAnimals, dailyTemplate: [] },
    );
    expect(m.groupAxis).toBe('col');
    expect(m.columns.map((c) => [c.group, c.label])).toEqual([['Control', 'Alpha'], ['Drug', 'Beta']]);
  });
  it('drops entirely-blank rows', () => {
    const statuses = [
      { animal_id: 'a1', date: '2026-07-01T00:00:00Z', analysis_summary: { total: 5 } },
      { animal_id: 'a1', date: '2026-07-05T00:00:00Z', analysis_summary: null },
    ];
    const m = buildSubjectSeriesMatrix(
      { xField: '__date__', dataParam: totalParam, groupField: '__none__' },
      { statuses, animals: ssAnimals, dailyTemplate: [] },
    );
    expect(m.rows.map((r) => r.member.label)).toEqual(['2026-07-01']);
  });
});
