import { readFile } from 'node:fs/promises';
import path from 'node:path';

import { describe, expect, it } from 'vitest';

const SERVER_PATH = path.join(import.meta.dirname, 'server.ts');
const ROW_PIPELINE_SYNC_PATH = path.join(import.meta.dirname, '..', 'pipelines', 'row-pipeline-sync.ts');

describe('search progress realtime metrics wiring', () => {
  it('persists progress_update metrics by normalizing and merging partial snapshots', async () => {
    const source = await readFile(SERVER_PATH, 'utf8');

    expect(source).toContain('type SearchProgressMetrics');
    expect(source).toContain('metrics?: SearchProgressMetrics');
    expect(source).toContain('function normalizeSearchProgressMetrics');
    expect(source).toContain('metrics: normalizeSearchProgressMetrics(record.metrics)');
    expect(source).toContain('metrics: normalizeSearchProgressMetrics(parsed.metrics)');
    expect(source).toContain('const previousMetrics = normalizeSearchProgressMetrics(previousProgress.metrics)');
    expect(source).toContain('const eventMetrics = normalizeSearchProgressMetrics(event.metrics)');
    expect(source).toContain('{ ...(previousMetrics ?? {}), ...eventMetrics }');
    expect(source).toContain('...(metrics ? { metrics } : {})');
  });

  it('emits fixed-runtime candidate, matched, judged, and contact metrics during search progress', async () => {
    const source = await readFile(ROW_PIPELINE_SYNC_PATH, 'utf8');

    expect(source).toContain('type SearchProgressMetrics');
    expect(source).toContain('metrics: params.metrics');
    expect(source).toContain('candidateCount: mergedCandidates.length');
    expect(source).toContain('judgedCount: Math.min(mergedCandidates.length, processedCandidates || totalCandidates || 0)');
    expect(source).toContain('nameMatchedCount: llmMatchedCandidates.filter');
    expect(source).toContain('const nameMatchedCount = matchedCandidates.length');
    expect(source).toContain('attemptedContactCount: attemptedCount');
    expect(source).toContain('qualifiedResultCount: qualifiedCount');
    expect(source).toContain('targetResultCount: targetQualifiedCount ?? null');
  });
});
