import { describe, expect, it } from 'vitest'
import {
  normalizeSessionUiMetadata,
  readSessionUiMetadataFromSnapshot,
  SESSION_QUEUE_LIMIT,
} from '../src/dimsdk/core/session-meta.ts'

describe('session metadata normalization', () => {
  it('normalizes queue items, sorts them, and filters invalid diagnostics', () => {
    const metadata = normalizeSessionUiMetadata({
      lastErrorCode: 'timeout',
      lastUpdatedAt: 42,
      pinnedMessageIds: [' a ', '', 'b'],
      queue: [
        { id: 'user-2', text: 'second', createdAt: 20, kind: 'user' },
        { id: 'steer-2', text: 'later steer', createdAt: 5, kind: 'steer', steeredAt: 30 },
        { id: 'steer-1', text: 'first steer', createdAt: 10, kind: 'steer', steeredAt: 15, config: {
          approvalsMode: 'strict',
          interleavedThinking: true,
          model: 'gpt-5',
          providerId: 'openai',
          temperature: 0.3,
        } },
        { id: '', text: 'ignored', createdAt: 1, kind: 'user' },
        { id: 'empty-text', text: '', createdAt: 2, kind: 'user' },
      ],
      reasoningDiagnosticsByTurn: {
        turnA: 'visible',
        turnB: 'invalid',
        '': 'none',
      },
      status: 'running',
      titleSuggestedAt: 99,
    })

    expect(metadata).toMatchObject({
      lastErrorCode: 'timeout',
      lastUpdatedAt: 42,
      pinnedMessageIds: ['a', 'b'],
      queueLength: 3,
      reasoningDiagnosticsByTurn: {
        turnA: 'visible',
      },
      status: 'running',
      titleSuggestedAt: 99,
    })
    expect(metadata.queue.map(item => item.id)).toEqual([
      'steer-1',
      'steer-2',
      'user-2',
    ])
    expect(metadata.queue[0]?.config).toEqual({
      approvalsMode: 'strict',
      interleavedThinking: true,
      model: 'gpt-5',
      providerId: 'openai',
      temperature: 0.3,
    })
  })

  it('caps the normalized queue length at the session queue limit', () => {
    const queue = Array.from({ length: SESSION_QUEUE_LIMIT + 2 }, (_, index) => ({
      createdAt: index + 1,
      id: `q-${index + 1}`,
      kind: 'user' as const,
      text: String(index + 1),
    }))

    const metadata = normalizeSessionUiMetadata({ queue })

    expect(metadata.queue).toHaveLength(SESSION_QUEUE_LIMIT)
    expect(metadata.queueLength).toBe(SESSION_QUEUE_LIMIT)
  })

  it('reads legacy metadata locations from snapshots without fallback casts', () => {
    const metadata = readSessionUiMetadataFromSnapshot({
      metadata: {
        dimAgentRuntime: {
          metadata: {
            ui: {
              queue: [{ createdAt: 1, id: 'q_1', kind: 'user', text: 'queued' }],
              status: 'paused_confirm',
            },
          },
        },
      },
    })

    expect(metadata.queue).toEqual([
      { createdAt: 1, id: 'q_1', kind: 'user', text: 'queued' },
    ])
    expect(metadata.queueLength).toBe(1)
    expect(metadata.status).toBe('paused_confirm')
  })
})
