import type { DimSdkSessionListItem } from '../../../keys'
import { stripLeadingFocusFilesBlock } from '#cli/core/focus-files'

function stripNewSessionPlaceholder(v: unknown): string {
  const s = String(v ?? '').trim()
  return s === 'New session' || s === 'New Thread' || s === '(empty)' ? '' : s
}

export function sanitizeSessionMetaForHeader(
  meta: DimSdkSessionListItem | null,
  firstUserPreview: string,
): DimSdkSessionListItem | null {
  if (!meta) return null

  // Only treat placeholder title/summary values during the short window where:
  // - the in-memory transcript already has a user message, but
  // - the persisted snapshot used by `sessions.list()` still reports messageCount=0.
  const preview = stripLeadingFocusFilesBlock(firstUserPreview).trim()
  if (!preview) return meta
  if (meta.messageCount > 0) return meta

  const title = stripNewSessionPlaceholder(meta.title)
  const summary = stripNewSessionPlaceholder(meta.summary)
  if (title !== meta.title || summary !== meta.summary)
    return { ...meta, title, summary }
  return meta
}

export function computeSessionHeaderSummary(
  meta: DimSdkSessionListItem | null,
  firstUserPreview: string,
): string {
  const preview = stripLeadingFocusFilesBlock(firstUserPreview).trim()
  const sanitized = sanitizeSessionMetaForHeader(meta, preview)

  const title = String(sanitized?.title ?? '').trim()
  if (title) return title

  const summary = String(sanitized?.summary ?? '').trim()
  if (summary) return summary

  return preview || 'New Thread'
}
