/** @vitest-environment jsdom */
import { describe, expect, it } from 'vitest'
import { extractQuarantine, isAttemptAlarmed } from './attempt-record'
import type { AttemptRecord } from './attempt-record'

const NOW_MS = Date.parse('2026-08-04T03:00:00.000Z')

describe('isAttemptAlarmed', () => {
  it('matches harness alarm thresholds', () => {
    const base: AttemptRecord = {
      attemptId: 'attempt-live',
      timeoutSecs: 120,
      liveness: {
        elapsedSecs: 30,
        lastActivity: 'thinking',
        lastSignalAt: '2026-08-04T02:59:30.000Z',
      },
    }

    expect(isAttemptAlarmed(base, NOW_MS)).toBe(false)
    expect(isAttemptAlarmed({ ...base, liveness: { ...base.liveness!, elapsedSecs: 250 } }, NOW_MS)).toBe(true)
    expect(isAttemptAlarmed({
      ...base,
      liveness: {
        elapsedSecs: 30,
        lastActivity: 'thinking',
        lastSignalAt: '2026-08-04T02:56:00.000Z',
      },
    }, NOW_MS)).toBe(true)
    expect(isAttemptAlarmed({ ...base, liveness: null }, NOW_MS)).toBe(false)
  })
})

describe('extractQuarantine', () => {
  const ev = (kind: string, payload: Record<string, unknown>, id: string) =>
    ({ id, source: 'journal', kind, ts: '2026-08-06T00:00:00.000Z', payload }) as never

  it('returns null when no quarantine event exists', () => {
    expect(extractQuarantine([ev('dispatch.attempt', {}, 'e1')])).toBeNull()
  })

  it('returns phase and reason of the latest quarantine event', () => {
    const events = [
      ev('quarantine', { phase: 'quality', reason: 'older reason' }, 'e1'),
      ev('dispatch.attempt', {}, 'e2'),
      ev('quarantine', { phase: 'quality', reason: 'review rejected twice' }, 'e3'),
    ]
    expect(extractQuarantine(events)).toEqual({ phase: 'quality', reason: 'review rejected twice' })
  })

  it('labels missing payload fields as not recorded', () => {
    expect(extractQuarantine([ev('quarantine', {}, 'e1')])).toEqual({ phase: 'not recorded', reason: 'not recorded' })
  })
})
