// @vitest-environment jsdom
import '../test/dom-setup';
import { describe, expect, it } from 'vitest';
import { reduceDelegateStreams, type DelegateStreamEntry } from './useJobStream';

type S = Record<string, DelegateStreamEntry>;

describe('reduceDelegateStreams', () => {
  it('lifecycle(running) で entry を生成', () => {
    const next = reduceDelegateStreams({}, {
      type: 'delegate_lifecycle', delegateRunId: 'r1', parentRunId: null, depth: 1,
      description: 'sub A', status: 'running',
    });
    expect(next.r1).toMatchObject({
      delegateRunId: 'r1', parentRunId: null, depth: 1, description: 'sub A',
      status: 'running', text: '', currentTool: null,
    });
  });
  it('delegate_text_delta で text を追記', () => {
    let s: S = reduceDelegateStreams({}, { type: 'delegate_lifecycle', delegateRunId: 'r1', parentRunId: null, depth: 1, description: 'A', status: 'running' });
    s = reduceDelegateStreams(s, { type: 'delegate_text_delta', delegateRunId: 'r1', text: 'foo' });
    s = reduceDelegateStreams(s, { type: 'delegate_text_delta', delegateRunId: 'r1', text: 'bar' });
    expect(s.r1.text).toBe('foobar');
    expect(s.r1.currentTool).toBeNull();
  });
  it('delegate_tool で currentTool をセット、text 到着で currentTool をクリア', () => {
    let s: S = reduceDelegateStreams({}, { type: 'delegate_lifecycle', delegateRunId: 'r1', parentRunId: null, depth: 1, description: 'A', status: 'running' });
    s = reduceDelegateStreams(s, { type: 'delegate_tool', delegateRunId: 'r1', toolName: 'WebFetch', toolInput: 'x' });
    expect(s.r1.currentTool).toBe('WebFetch');
    s = reduceDelegateStreams(s, { type: 'delegate_text_delta', delegateRunId: 'r1', text: 'y' });
    expect(s.r1.currentTool).toBeNull();
  });
  it('lifecycle(success) で status 更新、text は保持', () => {
    let s: S = reduceDelegateStreams({}, { type: 'delegate_lifecycle', delegateRunId: 'r1', parentRunId: null, depth: 1, description: 'A', status: 'running' });
    s = reduceDelegateStreams(s, { type: 'delegate_text_delta', delegateRunId: 'r1', text: 'keep' });
    s = reduceDelegateStreams(s, { type: 'delegate_lifecycle', delegateRunId: 'r1', parentRunId: null, depth: 1, description: 'A', status: 'success' });
    expect(s.r1.status).toBe('success');
    expect(s.r1.text).toBe('keep');
  });
  it('text が lifecycle より先に来ても entry を生成（順序耐性）', () => {
    const s = reduceDelegateStreams({}, { type: 'delegate_text_delta', delegateRunId: 'r1', text: 'early' });
    expect(s.r1?.text).toBe('early');
    expect(s.r1?.status).toBe('running');
  });
});
