import { describe, expect, it } from 'vitest'
import type { FactoryRunView } from '../../lib/factory-types'
import { factoryAgentHref, failureReasons, transcriptSteps } from './factory-run-view-helpers'

const run = (overrides: Partial<FactoryRunView> = {}): FactoryRunView => ({
  adwId: 'adw-55', repo: null, repoName: null, runSlug: null, adwName: null, request: null, status: 'failed', engineer: null,
  startedAt: null, endedAt: null, totalTokens: null, totalCost: null, events: [], decisions: [],
  phases: [{ phaseId: 'phase-2', seq: 2, name: 'verify', kind: 'gate', owner: null, description: null, status: null, attempt: 1, retries: null, error: null, startedAt: '2026-08-09T10:02:00.000Z', endedAt: null, durationMs: null, tokens: 0, spend: 0 }, { phaseId: 'phase-1', seq: 1, name: 'build', kind: 'agent', owner: null, description: null, status: null, attempt: 1, retries: null, error: null, startedAt: '2026-08-09T10:01:00.000Z', endedAt: '2026-08-09T10:01:30.000Z', durationMs: 30000, tokens: 0, spend: 0 }],
  attempts: [], diffs: [], gates: [], ...overrides,
})

describe('factory run transcript helpers', () => {
  it('orders phase-only artifacts and keeps every phase diff reachable', () => {
    const steps = transcriptSteps(run({ diffs: [
      { phaseId: 'phase-1', attempt: null, files: [], insertions: 1, deletions: 0, diffText: 'first', truncated: false, createdAt: null },
      { phaseId: 'phase-1', attempt: 1, files: [], insertions: 2, deletions: 1, diffText: 'second', truncated: false, createdAt: null },
    ] }))
    expect(steps.map(step => step.id)).toEqual(['phase-1', 'phase-2'])
    expect(steps[0]).toMatchObject({ type: 'phase', isStreaming: false })
    expect(steps[0]?.diffs).toHaveLength(2)
    expect(steps[1]).toMatchObject({ type: 'phase', isStreaming: true })
  })

  it('includes string-array gate violations in the terminal failure reasons', () => {
    expect(failureReasons(run({ gates: [{ adwId: 'adw-55', phaseId: 'phase-2', attempt: 1, gate: 'quality', passed: false, checks: [], violations: ['lint failed', 'test failed'] }] }))).toEqual(['lint failed', 'test failed'])
  })

  it('links an agent attempt through authoritative factory task identity', () => {
    const linkedRun = run({
      phases: [{ ...run().phases[1]!, taskId: 'build story' }],
      attempts: [{ attemptId: 'attempt-1', phaseId: 'phase-1' } as NonNullable<FactoryRunView['attempts']>[number]],
    })
    const attempt = transcriptSteps(linkedRun).find((step) => step.type === 'attempt')
    expect(attempt && factoryAgentHref(linkedRun, attempt)).toBe('/factory/adw-55/agents/build%20story')
  })

  it('withholds activity links from legacy phases without task identity', () => {
    const legacyRun = run({ attempts: [{ attemptId: 'attempt-1', phaseId: 'phase-1' } as NonNullable<FactoryRunView['attempts']>[number]] })
    const attempt = transcriptSteps(legacyRun).find((step) => step.type === 'attempt')
    expect(attempt && factoryAgentHref(legacyRun, attempt)).toBeUndefined()
  })
})
