import { describe, expect, it } from 'vitest'
import { projectAgentActivity, selectUniquePhaseDiff } from './agent-activity-projection'

const event = (id: string, kind: string, ts: string) => ({ id, source: 'run', kind, ts, taskId: 'task', attemptId: 'attempt', payload: {} })
describe('projectAgentActivity', () => {
  it('groups only adjacent routine activity with a stable first-event identity', () => {
    const result = projectAgentActivity([event('one', 'tool.read', '2026-08-14T00:00:00Z'), event('two', 'tool.read', '2026-08-14T00:00:01Z'), event('three', 'gate.result', '2026-08-14T00:00:02Z')])
    expect(result.items[0]).toMatchObject({ id: 'attempt:read:one', kind: 'group' })
    expect((result.items[0] as { children: unknown[] }).children).toHaveLength(2)
    expect(result.items[1]).toMatchObject({ kind: 'test' })
  })
  it('selects by the complete identity chain before requiring uniqueness', () => {
    const editEvent = { ...event('edit', 'tool.edit', '2026-08-14T00:00:00Z'), phaseId: 'phase', payload: { path: 'src/a.ts' } }
    const base = { adwId: 'run', taskId: 'task', phaseId: 'phase', attempt: 1, files: [{ path: 'src/a.ts', status: 'M', insertions: 1, deletions: 0 }], insertions: 1, deletions: 0, diffText: 'right', truncated: false, createdAt: null, linkage: 'linked' as const }
    const selected = selectUniquePhaseDiff(editEvent, 'run', 'src/a.ts', [
      { ...base, attemptId: 'other', diffText: 'wrong' },
      { ...base, attemptId: 'attempt', diffText: 'right' },
    ])
    expect(selected?.diffText).toBe('right')
  })
  it('keeps the first conflicting duplicate and makes unknown records readable', () => {
    const result = projectAgentActivity([{ ...event('same', 'unknown', '2026-08-14T00:00:00Z'), payload: { text: 'Human text' } }, { ...event('same', 'unknown', '2026-08-14T00:00:01Z'), payload: { text: 'Changed' } }])
    expect(result.items.at(-1)).toMatchObject({ title: 'Recorded activity', summary: 'Human text' })
    expect(result.warnings[0]?.title).toBe('Conflicting activity record')
  })
})
