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

import { emptyPaper, publishPaper, type Paper } from './paperModel';
import {
  OPERATING_PRINCIPLES,
  statusFromPapers,
  humanApprovalIntact,
} from './governance';

function readyDraft(): Paper {
  return {
    ...emptyPaper(),
    title: 'T',
    abstractVi: 'A',
    body: 'B',
    sources: [{ id: 's1', title: 'S', verifiedReal: true }],
  };
}

describe('governance', () => {
  it('exposes the four operating principles, one flagged danger (INV-4 gate)', () => {
    expect(OPERATING_PRINCIPLES).toHaveLength(4);
    expect(OPERATING_PRINCIPLES.filter((p) => p.tone === 'danger')).toHaveLength(1);
    expect(OPERATING_PRINCIPLES.map((p) => p.id)).toEqual(['inv-1', 'inv-2', 'inv-3', 'inv-4']);
  });

  it('statusFromPapers counts published vs drafts and integrity-blocked drafts', () => {
    const blocked = emptyPaper(); // no title/abstract/body/sources → blocked
    const ready = readyDraft();
    const published = publishPaper(readyDraft(), { id: 'u1', name: 'TS. An' });

    const s = statusFromPapers([blocked, ready, published]);
    expect(s.totalPapers).toBe(3);
    expect(s.published).toBe(1);
    expect(s.drafts).toBe(2);
    expect(s.draftsBlockedByIntegrity).toBe(1);
    expect(s.draftsReadyToPublish).toBe(1);
    expect(s.publishedWithApproval).toBe(1);
  });

  it('humanApprovalIntact (INV-1) is true when every published paper has an approval', () => {
    const published = publishPaper(readyDraft(), { id: 'u1', name: 'TS. An' });
    expect(humanApprovalIntact(statusFromPapers([published]))).toBe(true);
  });

  it('humanApprovalIntact is false if a published paper lacks an approval record', () => {
    const forged: Paper = { ...readyDraft(), status: 'published', approval: null };
    expect(humanApprovalIntact(statusFromPapers([forged]))).toBe(false);
  });

  it('an empty corpus is trivially compliant', () => {
    const s = statusFromPapers([]);
    expect(s.totalPapers).toBe(0);
    expect(humanApprovalIntact(s)).toBe(true);
  });
});
