import { describe, it, expect, vi } from 'vitest';
import type { AgentOrchestrator } from '../backends/native/orchestrator.js';
import { summarizeSessionOnEnd, sessionEndSummaryInternals } from './endSummary.js';
import type { MemoryStore } from '../memory/store.js';

describe('session end summary', () => {
  it('sanitizes session ids for memory namespaces', () => {
    expect(sessionEndSummaryInternals.sanitizeSessionId('ws:abc-123')).toBe('ws/abc-123');
    expect(sessionEndSummaryInternals.sanitizeSessionId('telegram:user@x')).toBe('telegram/user_x');
  });

  it('summarizes and writes to memory when enabled', async () => {
    const agent = {
      delegate: vi.fn().mockResolvedValue({
        content: '- User prefers concise responses.\n- Next step: run deploy tomorrow.',
        usage: { inputTokens: 10, outputTokens: 8 },
        tier: 'fast',
      }),
    } as unknown as AgentOrchestrator;
    const memoryStore = {
      write: vi.fn(),
    } as unknown as MemoryStore;

    const result = await summarizeSessionOnEnd({
      agent,
      sessionId: 'ws:conn-1',
      history: [
        { role: 'user', content: 'Please keep answers concise.' },
        { role: 'assistant', content: 'Noted.' },
      ],
      config: {
        enabled: true,
        tier: 'fast',
        maxMessages: 50,
        maxInputChars: 20000,
        maxTokens: 512,
        writeToMemory: true,
        memoryNamespace: 'session/summaries',
      },
      memoryStore,
    });

    expect(agent.delegate).toHaveBeenCalledTimes(1);
    expect(result?.summary).toContain('concise');
    expect(result?.namespace).toBe('session/summaries/ws/conn-1');
    expect(memoryStore.write).toHaveBeenCalledWith(
      'session/summaries/ws/conn-1',
      expect.stringContaining('User prefers concise responses'),
      'append',
    );
  });

  it('skips when disabled', async () => {
    const agent = {
      delegate: vi.fn(),
    } as unknown as AgentOrchestrator;

    const result = await summarizeSessionOnEnd({
      agent,
      sessionId: 'ws:conn-1',
      history: [{ role: 'user', content: 'hello' }],
      config: {
        enabled: false,
        tier: 'fast',
        maxMessages: 50,
        maxInputChars: 20000,
        maxTokens: 512,
        writeToMemory: true,
        memoryNamespace: 'session/summaries',
      },
    });

    expect(result).toBeNull();
    expect(agent.delegate).not.toHaveBeenCalled();
  });
});
