import { readFile, writeFile } from 'node:fs/promises'
import { buildInitialCodeMdTemplate } from '../codeMdTemplate.js'
import { assertWithinSize, mergeSectionIntoCodeMd } from '../mergeSection.js'
import { getCodeMdPath } from '../memory/loadCodeMd.js'
import { requireCodeWorkDir } from '../hooks.js'

export type RecordInput = {
  section: string
  content: string
  mode: 'upsert' | 'append'
}

/** 增量更新 code.md（仅分区 merge，禁止整文件覆盖） */
export async function runRecord(input: RecordInput): Promise<Record<string, unknown>> {
  const codeWorkDir = requireCodeWorkDir()
  const codeMdPath = getCodeMdPath(codeWorkDir)
  let existing: string
  try {
    existing = await readFile(codeMdPath, 'utf8')
  } catch {
    existing = buildInitialCodeMdTemplate()
  }
  const merged = mergeSectionIntoCodeMd(
    existing,
    input.section,
    input.content,
    input.mode,
  )
  assertWithinSize(merged)
  await writeFile(codeMdPath, merged, 'utf8')
  return {
    path: codeMdPath,
    section: input.section,
    mode: input.mode,
    size: merged.length,
  }
}
