/**
 * Helper functions for ChunkBrowserQA component.
 */

import { REGULATION_INFO } from '../rag-constants'

/** Get text content from a chunk */
export function getChunkText(chunk: Record<string, unknown> | null): string {
  if (!chunk) return ''
  return String(chunk.chunk_text || chunk.text || chunk.content || '')
}

/** Extract structural metadata for prominent display */
export function getStructuralInfo(
  chunk: Record<string, unknown> | null
): { article?: string; section?: string; pages?: string } {
  if (!chunk) return {}
  const result: { article?: string; section?: string; pages?: string } = {}
  // Article / paragraph
  const article = chunk.article || chunk.artikel || chunk.paragraph || chunk.section_title
  if (article) result.article = String(article)
  // Section
  const section = chunk.section || chunk.chapter || chunk.abschnitt || chunk.kapitel
  if (section) result.section = String(section)
  // Pages
  const pages = chunk.pages as number[] | undefined
  if (Array.isArray(pages) && pages.length > 0) {
    result.pages = pages.length === 1 ? `S. ${pages[0]}` : `S. ${pages[0]}-${pages[pages.length - 1]}`
  } else if (chunk.page) {
    result.pages = `S. ${chunk.page}`
  }
  return result
}

/** Regulation name lookup */
export function getRegName(code: string): string {
  const reg = REGULATION_INFO.find(r => r.code === code)
  return reg?.name || code
}
