import assert from 'node:assert/strict';
import test from 'node:test';
import { autoResumeLabel, blockReasonLabel, overlayCollapsedLines, policyLabel, relativeAge, stallDescription } from '../src/presentation.js';
import type { ContinuityWorkerView } from '../src/ui-model.js';

const worker: ContinuityWorkerView = {
  workerId: 'wrk_00000000-0000-0000-0000-000000000001',
  label: 'UI migration',
  hierarchicalName: '/root/ui',
  assignmentTitle: 'UI migration',
  runId: null,
  runTitle: null,
  conversationState: 'idle',
  conversationUrl: 'https://chatgpt.com/c/one',
  statusLabel: 'Resuming',
  tabId: 7,
  currentTab: true,
  policyMode: 'auto',
  policySource: 'worker',
  attemptNumber: 5,
  autoResumeCount: 4,
  lastProgressAt: '2026-08-21T03:00:00.000Z',
  blockReason: null,
  pauseReason: null,
  noProgressAttempts: null,
  stallWarningAt: null,
  stallPausedAt: null,
  stallState: 'unavailable',
  recentEvents: null,
  needsUser: false,
  controlAvailable: true,
};

test('popup/overlay presentation uses operator terms and distinguishes worker policy override', () => {
  assert.equal(policyLabel(worker), 'Auto Resume On · Worker override');
  assert.deepEqual(overlayCollapsedLines(worker), { primary: 'Orchestrated · Auto Resume', detail: 'Continuing · Attempt 5' });
  assert.equal(autoResumeLabel('mixed'), 'Mixed worker policies');
});

test('progress ages are compact and do not invent a timestamp', () => {
  assert.equal(relativeAge(null, Date.parse('2026-08-21T04:00:00.000Z')), 'No durable progress yet');
  assert.equal(relativeAge('2026-08-21T03:30:00.000Z', Date.parse('2026-08-21T04:00:00.000Z')), '30m ago');
  assert.equal(relativeAge('2026-08-20T04:00:00.000Z', Date.parse('2026-08-21T04:00:00.000Z')), '1d ago');
});

test('stall UX explicitly reports unavailable backend telemetry rather than inferring a stall', () => {
  assert.match(stallDescription(worker), /not exposed by the current backend UI contract/i);
  const warned: ContinuityWorkerView = { ...worker, stallState: 'warning', noProgressAttempts: 10 };
  assert.match(stallDescription(warned), /10 attempts without durable progress/i);
});

test('block reason fallback stays explicit when detailed backend reason is unavailable', () => {
  const needsUser: ContinuityWorkerView = { ...worker, statusLabel: 'Needs you', needsUser: true };
  assert.match(blockReasonLabel(needsUser), /detailed reason is unavailable/i);
  assert.equal(blockReasonLabel({ ...worker, blockReason: 'Approve production access' }), 'Approve production access');
});
