import { MAX_MEMORY_CHARACTER_COUNT } from './memory/constants.js'

const KNOWN_SECTIONS = new Set([
  'overview',
  'architecture',
  'commands',
  'gotchas',
  'patterns',
  'learnings',
])

function normalizeHeading(name: string): string {
  return name.trim().toLowerCase()
}

/**
 * 将 content 合并进 markdown 的 ## section。
 * mode=upsert 替换该节正文；append 在节末追加带日期的列表项。
 */
export function mergeSectionIntoCodeMd(
  existing: string,
  section: string,
  content: string,
  mode: 'upsert' | 'append',
): string {
  const key = normalizeHeading(section)
  const heading =
    key === 'learnings' || !KNOWN_SECTIONS.has(key)
      ? 'Learnings'
      : section.charAt(0).toUpperCase() + section.slice(1).toLowerCase()

  const sectionRegex = new RegExp(
    `(^##\\s+${escapeRegExp(heading)}\\s*$)([\\s\\S]*?)(?=^##\\s+|\\Z)`,
    'im',
  )
  const trimmedContent = content.trim()
  const dateLine = `- ${new Date().toISOString().slice(0, 10)}: ${trimmedContent.replace(/\n/g, ' ')}`

  if (sectionRegex.test(existing)) {
    return existing.replace(sectionRegex, (_m, h: string, body: string) => {
      const prev = body.trim()
      if (mode === 'append') {
        if (prev.includes(trimmedContent)) return `${h}\n\n${prev}\n`
        return `${h}\n\n${prev}\n${dateLine}\n`
      }
      return `${h}\n\n${trimmedContent}\n\n`
    })
  }

  const block =
    mode === 'append'
      ? `## ${heading}\n\n${dateLine}\n`
      : `## ${heading}\n\n${trimmedContent}\n`
  return `${existing.trimEnd()}\n\n${block}`
}

function escapeRegExp(s: string): string {
  return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

/** 合并后超过上限则抛错（fail-fast） */
export function assertWithinSize(text: string): void {
  if (text.length > MAX_MEMORY_CHARACTER_COUNT) {
    throw new Error(
      `code.md 超过 ${MAX_MEMORY_CHARACTER_COUNT} 字符，请精简后再 record`,
    )
  }
}
