/**
 * CppBuilder - Build C++ project
 * DD §15. build→CppBuildOutput; diagnostics via DiagnosticParser.
 *
 * @module packages/toolchain-cpp/src/build/CppBuilder
 */

import { execFileSync } from 'child_process'
import { DiagnosticParser, type ParsedDiagnostic } from '../analysis/DiagnosticParser.js'

export interface BuildOutput {
  ok: boolean
  output: string
  diagnostics: ParsedDiagnostic[]
  elapsed_ms: number
}

export class CppBuilder {
  private parser: DiagnosticParser

  constructor() {
    this.parser = new DiagnosticParser()
  }

  build(build_dir: string, target?: string): BuildOutput {
    const start = Date.now()
    const args = ['--build', '.', ...(target ? ['--target', target] : [])]

    try {
      const output = execFileSync('cmake', args, {
        cwd: build_dir,
        encoding: 'utf-8',
        stdio: 'pipe',
      })

      return {
        ok: true,
        output,
        diagnostics: this.parser.parse_compiler_output(output),
        elapsed_ms: Date.now() - start
      }
    } catch (error) {
      const err = error as { stdout?: string; stderr?: string; message?: string }
      const output = [err.stdout, err.stderr].filter(Boolean).join('\n')

      return {
        ok: false,
        output,
        diagnostics: this.parser.parse_compiler_output(output),
        elapsed_ms: Date.now() - start
      }
    }
  }
}
