import { describe, expect, it } from 'vitest';
import { formatActivityLogEntry, formatActivityLogMetadata, formatDuration, parseActivityLogMetadata, summarizeToolInput, truncateLogText } from './log-format.js';

describe('activity log format', () => {
  it('prepends worker and mode metadata to entries', () => {
    expect(formatActivityLogMetadata({ workerId: 'worker-148', mode: 'quality' })).toBe('[worker:worker-148] [mode:quality]');
    expect(formatActivityLogEntry('[understand] start', { workerId: 'worker-148', mode: 'quality' }))
      .toBe('[worker:worker-148] [mode:quality] [understand] start');
  });

  it('parses metadata from a log line', () => {
    expect(parseActivityLogMetadata('[2026-03-13T00:00:00.000Z] [worker:worker-074] [mode:fast] Read: {"file_path":"input/a.png"}')).toEqual({
      workerId: 'worker-074',
      mode: 'fast',
    });
  });

  it('handles lines without metadata', () => {
    expect(formatActivityLogEntry('final: completed')).toBe('final: completed');
    expect(parseActivityLogMetadata('[2026-03-13T00:00:00.000Z] final: completed')).toEqual({
      workerId: null,
      mode: null,
    });
  });

  it('keeps metadata parsing stable for preview lines', () => {
    expect(parseActivityLogMetadata('[2026-03-13T00:00:00.000Z] [worker:worker-148] [mode:quality] [execute] preview: checked draft')).toEqual({
      workerId: 'worker-148',
      mode: 'quality',
    });
  });

  it('summarizes common tool inputs for activity logs', () => {
    expect(summarizeToolInput('Read', { file_path: 'input/a.png' })).toBe('input/a.png');
    expect(summarizeToolInput('Bash', { command: 'python script.py --input input/a.png --output output/a.md' })).toContain('python script.py');
  });

  it('normalizes preview text before truncation', () => {
    expect(truncateLogText('line 1\nline 2', 40)).toBe('line 1 line 2');
  });

  it('formats sub-second durations in milliseconds, ≥1s in seconds with one decimal', () => {
    expect(formatDuration(0)).toBe('0ms');
    expect(formatDuration(42)).toBe('42ms');
    expect(formatDuration(999)).toBe('999ms');
    expect(formatDuration(1_000)).toBe('1.0s');
    expect(formatDuration(2_812)).toBe('2.8s');
    expect(formatDuration(132_884)).toBe('132.9s');
  });

  it('treats negative and non-finite durations defensively', () => {
    expect(formatDuration(-1)).toBe('?');
    expect(formatDuration(Number.NaN)).toBe('?');
    expect(formatDuration(Number.POSITIVE_INFINITY)).toBe('?');
  });
});
