import { readFile, writeFile } from 'node:fs/promises'
import { assertApplyPathAllowed, resolveInWorkDir } from '../pathGuard.js'
import { requireCodeWorkDir } from '../hooks.js'

type PatchOp = { path: string; old_string: string; new_string: string }

export async function runApply(
  patches: PatchOp[],
): Promise<Record<string, unknown>> {
  const results: { path: string; ok: boolean; error?: string }[] = []
  for (const p of patches) {
    assertApplyPathAllowed(p.path)
    try {
      const full = resolveInWorkDir(requireCodeWorkDir(), p.path)
      const content = await readFile(full, 'utf8')
      if (!content.includes(p.old_string)) {
        results.push({ path: p.path, ok: false, error: 'old_string not found' })
        continue
      }
      const next = content.replace(p.old_string, p.new_string)
      await writeFile(full, next, 'utf8')
      results.push({ path: p.path, ok: true })
    } catch (e) {
      results.push({
        path: p.path,
        ok: false,
        error: e instanceof Error ? e.message : String(e),
      })
    }
  }
  return { patches: results }
}
