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

function execGit(args: string[], cwd: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const child = spawn('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] })
    let out = ''
    let err = ''
    child.stdout.on('data', (d: Buffer) => {
      out += d.toString()
    })
    child.stderr.on('data', (d: Buffer) => {
      err += d.toString()
    })
    child.on('close', code => {
      if (code !== 0) {
        reject(new Error(err.trim() || `git ${args.join(' ')} failed`))
        return
      }
      resolve(out)
    })
  })
}

export async function runStatus(): Promise<Record<string, unknown>> {
  const cwd = requireCodeWorkDir()
  const status = await execGit(['status', '--short'], cwd)
  let diffStat = ''
  try {
    diffStat = await execGit(['diff', '--stat'], cwd)
  } catch {
    diffStat = ''
  }
  return { status, diffStat }
}
