/**
 * SET 41 — clone-safe persist + honest empty pipeline-log labels.
 */
import { describe, expect, it } from 'vitest';
import {
  cloneSafeForPersist,
  emptyPipelineLogLabel,
  formatPersistFailed,
  RUN_RECORD_MISSING,
} from '../src/tier1/persistSafe';
import { eventTone, toneForKind } from '../src/tier1/eventTone';

describe('SET 41b cloneSafeForPersist', () => {
  it('round-trips a record that contains a Map so persist is not aborted', () => {
    const record = {
      id: '85d2fc54',
      events: [{ ts: '2026-07-26T00:00:00.000Z', phase: 'done', featureId: null, message: 'ok' }],
      // Suspected 37e ship shape: pages-adjacent Map that structured-clone rejects
      // when nested under some hosts; JSON path must still succeed.
      hostile: new Map([['spec', { chars: 12 }], ['contract', { chars: 8 }]]),
      nested: { bag: new Set(['a', 'b']), n: undefined as unknown },
    };
    const safe = cloneSafeForPersist(record);
    expect(safe.id).toBe('85d2fc54');
    expect(safe.hostile).toEqual({ spec: { chars: 12 }, contract: { chars: 8 } });
    expect(safe.nested.bag).toEqual(['a', 'b']);
    // undefined dropped by JSON
    expect('n' in (safe.nested as object)).toBe(false);
    // Structured-clone of the sanitized value must not throw.
    expect(() => structuredClone(safe)).not.toThrow();
  });

  it('breaks cycles instead of throwing', () => {
    const a: { self?: unknown; id: string } = { id: 'cyc' };
    a.self = a;
    const safe = cloneSafeForPersist(a);
    expect(safe.id).toBe('cyc');
    expect(safe.self).toBeNull();
    expect(() => structuredClone(safe)).not.toThrow();
  });

  it('stringifies bigints', () => {
    expect(cloneSafeForPersist({ n: 1n })).toEqual({ n: '1' });
  });
});

describe('SET 41a formatPersistFailed + red tone', () => {
  it('formats the canonical red log line', () => {
    expect(formatPersistFailed('Object could not be cloned.'))
      .toBe('persist failed: Object could not be cloned.');
    expect(formatPersistFailed('  ')).toBe('persist failed: unknown');
  });

  it('classifies persist failed lines as red', () => {
    expect(toneForKind('persist-failed')).toBe('red');
    expect(eventTone({ message: 'persist failed: Object could not be cloned.', phase: 'done' }))
      .toBe('red');
  });
});

describe('SET 41c emptyPipelineLogLabel', () => {
  it('never says starting… for a finished/cancelled current id', () => {
    expect(emptyPipelineLogLabel({ isCurrent: true, running: false }))
      .toBe(RUN_RECORD_MISSING);
    expect(emptyPipelineLogLabel({ isCurrent: true, running: true }))
      .toBe('starting…');
  });

  it('marks missing prior records honestly', () => {
    expect(emptyPipelineLogLabel({ isCurrent: false, recordMissing: true }))
      .toBe(RUN_RECORD_MISSING);
    expect(emptyPipelineLogLabel({ isCurrent: false, recordMissing: false }))
      .toBe('no events saved for this epoch');
  });
});
