import type { TokenType } from '../types'

export function createContentPreview(tokens: TokenType[], maxLength: number = 20): string {
  return tokens
    .slice(0, 3)
    .map(token => token.content)
    .join('')
    .slice(0, maxLength)
}

export function createLineKey(line: TokenType[], index: number) {
  const contentPreview = createContentPreview(line)
  return `line-${index}-${contentPreview}`
}

export function removeExtraIndentation(text: string): string {
  const preserved = text.replace(/\\n/g, '§NEWLINE§')
  const lines = preserved.split('\n')
  const minIndent = Math.min(
    ...lines
      .filter(line => line.trim().length > 0)
      .map(line => line.match(/^\s*/)?.[0].length ?? 0),
  )

  const normalized = lines
    .map((line) => {
      if (line.trim().length === 0)
        return ''

      const indent = line.match(/^\s*/)?.[0] ?? ''
      const relativeIndent = ' '.repeat(Math.max(0, indent.length - minIndent))
      return relativeIndent + line.trim()
    })
    .join('\n')

  return normalized.replace(/§NEWLINE§/g, '\\n')
}
