import type { Message } from '#cli/core/model'
import type {
  ReasoningDiagnosticsByTurn,
  SessionQueueItem,
  SessionQueueStatus,
} from '#cli/core/session-meta'
import type { InjectionKey } from 'vue'
import type { CliAgentBridge as DimSdkAgent } from './agent-bridge'
import type { DimSdkStore } from './core/store'

export type DimSdkSessionListItem = Readonly<{
  id: string
  updatedAt: number
  cwd?: string
  title: string
  summary: string
  messageCount: number
  lastMessage?: string
  status?: SessionQueueStatus
  queueLength?: number
  queue?: readonly SessionQueueItem[]
  lastUpdatedAt?: number
  reasoningDiagnosticsByTurn?: ReasoningDiagnosticsByTurn
}>

export type DimSdkSessionTraceEvent = Readonly<{
  sequence: number
  at: number
  type: string
  summary: string
}>

export type DimSdkSessionTraceRequest = Readonly<{
  id: string
  index: number
  kind: 'turn' | 'session'
  status: string
  turnId?: string
  startedAt?: number
  completedAt?: number
  promptPreview?: string
  assistantPreview?: string
  userMessageCount: number
  assistantMessageCount: number
  toolCallCount: number
  childTaskCount: number
  compactionCount: number
  runCount: number
  eventCount: number
  events: readonly DimSdkSessionTraceEvent[]
}>

export type DimSdkSessionTrace = Readonly<{
  threadId: string
  generatedAt: number
  eventCount: number
  requests: readonly DimSdkSessionTraceRequest[]
}>

export type DimSdkSessionsApi = Readonly<{
  list: () => Promise<readonly DimSdkSessionListItem[]>
  get?: (id: string) => Promise<unknown | null>
  trace?: (id: string) => Promise<DimSdkSessionTrace | null>
  reload?: (id: string) => Promise<boolean>
  use: (id: string) => Promise<void>
  createNew: () => Promise<void>
  delete: (id: string) => Promise<void>
  rename?: (id: string, title: string) => Promise<void>
  fork?: (opts: Readonly<{ messages: readonly Message[] }>) => Promise<void>
  updateMetadata?: (
    id: string,
    metadata: Record<string, unknown>,
  ) => Promise<void>
}>

export type DimSdkAppBridge = Readonly<{
  store: DimSdkStore
  sessions?: DimSdkSessionsApi
  agent?: DimSdkAgent
  uiForcedSkills?: Set<string>
}>

export const DimSdkBridgeKey: InjectionKey<DimSdkAppBridge> =
  Symbol('DimSdkBridge')
