/**
 * D3 regression: Worker result WorkerResult<T> envelope
 * Validates that WorkerManager has the result field on WorkerHandle,
 * wrap_worker_result and get_result methods, and imports WorkerResult
 * from contracts.
 *
 * Uses source inspection (reading the source file as text).
 */

import { describe, it, expect } from 'bun:test'
import { readFileSync } from 'fs'
import { join } from 'path'

const source_path = join(import.meta.dir, '../../src/workers/WorkerManager.ts')
const source = readFileSync(source_path, 'utf-8')

describe('D3: Worker result envelope', () => {
  it('WorkerHandle has result field', () => {
    expect(source).toContain('result?: WorkerResult<unknown>')
  })

  it('wrap_worker_result method exists', () => {
    expect(source).toContain('wrap_worker_result(')
    // Should be a private method
    expect(source).toContain('private wrap_worker_result')
  })

  it('get_result method exists', () => {
    expect(source).toContain('get_result(agent_id: string)')
    // Should return WorkerResult<unknown> | undefined
    expect(source).toContain('WorkerResult<unknown> | undefined')
  })

  it('imports WorkerResult from contracts', () => {
    expect(source).toContain("import type { WorkerResult")
    expect(source).toContain("from '@aircoding/contracts'")
  })

  it('imports WorkerStatus from contracts', () => {
    expect(source).toContain('WorkerStatus')
  })

  it('imports AgentType from contracts', () => {
    expect(source).toContain('AgentType')
  })

  it('wrap_worker_result returns WorkerResult with safe defaults', () => {
    // Verify safe defaults for key fields
    expect(source).toContain("agent_type: (payload.agent_type as AgentType) || 'executor'")
    expect(source).toContain("status: (payload.status as WorkerStatus) || 'completed'")
    expect(source).toContain("summary: (payload.summary as string) || ''")
    expect(source).toContain('changed_files: (payload.changed_files as string[]) || []')
    expect(source).toContain('artifacts: (payload.artifacts as any[]) || []')
    expect(source).toContain('verification: (payload.verification as any[]) || []')
    expect(source).toContain('risks: (payload.risks as any[]) || []')
    expect(source).toContain('follow_up_tasks: (payload.follow_up_tasks as any[]) || []')
    expect(source).toContain('evidence_refs: (payload.evidence_refs as any[]) || []')
  })

  it('get_result returns undefined for unknown agent', () => {
    // The method should check if handle exists and return undefined
    expect(source).toContain('if (!handle) return undefined')
  })
})
