import { buildSessionTreeSnapshot } from '../src/modules/netaclaw/session-tree/snapshot.js';
import type {
  SessionTreeEntry,
  SessionTreeSession,
} from '../src/modules/netaclaw/session-tree/types.js';

describe('session tree snapshot subagent projection', () => {
  it('projects subagent result metadata consistently for entries and active path without mutating source entries', () => {
    const session: SessionTreeSession = {
      sessionId: 'session-subagent-projection-snapshot',
      provider: 'file',
      rootEntryId: 'root',
      leafEntryId: 'subagent-result',
    };
    const entries: SessionTreeEntry[] = [
      {
        id: 'root',
        parentId: null,
        timestamp: '2026-04-19T00:00:00.000Z',
        type: 'message',
        message: { role: 'user', content: 'run subagents' },
      },
      {
        id: 'subagent-result',
        parentId: 'root',
        timestamp: '2026-04-19T00:01:00.000Z',
        type: 'subagent_result',
        content: {
          batchId: 'batch-subagent-result',
          results: [
            {
              id: 'subagent_1',
              status: 'completed',
              summary: 'found 2 images',
            },
          ],
          status: 'completed',
          parentEntryId: 'root',
        },
      },
    ];

    const snapshot = buildSessionTreeSnapshot(session, entries);
    const projectedEntry = snapshot.entries.find(entry => entry.id === 'subagent-result');
    const projectedPathEntry = snapshot.activePath.find(entry => entry.id === 'subagent-result');

    expect(projectedEntry?.metadata?.subagentProjection).toMatchObject({
      version: 1,
      source: 'backend-projection',
      taskPanels: [
        {
          key: 'subagent_1',
          summary: 'found 2 images',
        },
      ],
    });
    expect(projectedPathEntry?.metadata?.subagentProjection).toEqual(projectedEntry?.metadata?.subagentProjection);
    expect(entries[1].metadata?.subagentProjection).toBeUndefined();
  });
});
