import { spawn } from 'node:child_process'
import { resolveInWorkDir } from '../pathGuard.js'
import { requireCodeWorkDir } from '../hooks.js'

export async function runSearch(
  pattern: string,
  glob?: string,
): Promise<Record<string, unknown>> {
  const cwd = requireCodeWorkDir()
  const args = ['--json', pattern, cwd]
  if (glob) {
    args.splice(1, 0, '-g', glob)
  }
  return new Promise((resolve, reject) => {
    const child = spawn('rg', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] })
    let stdout = ''
    let stderr = ''
    child.stdout.on('data', (d: Buffer) => {
      stdout += d.toString()
    })
    child.stderr.on('data', (d: Buffer) => {
      stderr += d.toString()
    })
    child.on('close', code => {
      if (code === 1) {
        resolve({ matches: [], pattern })
        return
      }
      if (code !== 0) {
        reject(new Error(stderr.trim() || `rg exit ${code}`))
        return
      }
      try {
        const lines = stdout
          .trim()
          .split('\n')
          .filter(Boolean)
          .slice(0, 100)
          .map(l => JSON.parse(l) as unknown)
        resolve({ pattern, matches: lines })
      } catch (e) {
        reject(e)
      }
    })
  })
}
