import { describe, expect, it } from 'vitest';
import { projectFilePath } from '@learnitive/project-storage';
import { inspectDelimitedDatasetBytes } from './project-dataset-service';

const encode = (text: string) => new TextEncoder().encode(text);

describe('inspectDelimitedDatasetBytes', () => {
  it('inspects quoted CSV deterministically without giving the model raw-file semantics', () => {
    const report = inspectDelimitedDatasetBytes(
      projectFilePath('data/experiment.csv'),
      encode('time,response,condition\n1,2.5,A\n2,,A\n3,7.5,"B, treated"\n'),
      { sampleRows: 2 },
    );

    expect(report.rowCount).toBe(3);
    expect(report.columnCount).toBe(3);
    expect(report.columns[0]).toMatchObject({ name: 'time', inferredType: 'integer', missingCount: 0 });
    expect(report.columns[1]).toMatchObject({ name: 'response', inferredType: 'number', missingCount: 1 });
    expect(report.columns[1]?.numeric?.mean).toBe(5);
    expect(report.columns[2]?.topValues?.some((item) => item.value === 'B, treated')).toBe(true);
    expect(report.sampleRows).toHaveLength(2);
  });

  it('handles TSV types and reports malformed rows rather than silently reshaping them', () => {
    const report = inspectDelimitedDatasetBytes(
      projectFilePath('data/study.tsv'),
      encode('date\tactive\tvalue\n2026-01-01\ttrue\t1\n2026-01-02\tfalse\t2\textra\n'),
    );

    expect(report.columns.map((column) => column.inferredType)).toEqual(['date', 'boolean', 'integer']);
    expect(report.malformedRowCount).toBe(1);
    expect(report.warnings.join(' ')).toMatch(/different field count/u);
  });
});

describe('datasetBytesToLatexTable', () => {
  it('escapes LaTeX-sensitive cells and emits a deterministic table', async () => {
    const { datasetBytesToLatexTable } = await import('./project-dataset-service');
    const table = datasetBytesToLatexTable(
      projectFilePath('results/model-summary.csv'),
      encode('term,estimate,note\nalpha_1,2.5,"95% & stable"\nbeta,3.0,$value\n'),
    );

    expect(table.latex).toContain('\\begin{table}[htbp]');
    expect(table.latex).toContain('alpha\\_1');
    expect(table.latex).toContain('95\\% \\& stable');
    expect(table.latex).toContain('\\$value');
    expect(table.latex).toContain('\\label{tab:model-summary}');
    expect(table.truncatedRows).toBe(false);
    expect(table.truncatedColumns).toBe(false);
  });

  it('reports row and column truncation explicitly', async () => {
    const { datasetBytesToLatexTable } = await import('./project-dataset-service');
    const table = datasetBytesToLatexTable(
      projectFilePath('results/wide.csv'),
      encode('a,b,c\n1,2,3\n4,5,6\n'),
      { maxRows: 1, maxColumns: 2 },
    );

    expect(table.includedRows).toBe(1);
    expect(table.includedColumns).toBe(2);
    expect(table.truncatedRows).toBe(true);
    expect(table.truncatedColumns).toBe(true);
  });
});
