/**
 * CppTestRunner - Run C++ tests
 * DD §15. run_tests→CppTestOutput.
 *
 * @module packages/toolchain-cpp/src/test/CppTestRunner
 */

import { execSync } from 'child_process'
import { DiagnosticParser } from '../analysis/DiagnosticParser.js'

export interface CppTestOutput {
  ok: boolean
  total: number
  passed: number
  failed: number
  output: string
  elapsed_ms: number
}

export class CppTestRunner {
  run_tests(build_dir: string): CppTestOutput {
    const start = Date.now()

    try {
      const output = execSync('ctest --output-on-failure', {
        cwd: build_dir,
        encoding: 'utf-8',
        stdio: 'pipe'
      })

      const { total, passed, failed } = this.parse_ctest_output(output)

      return {
        ok: failed === 0,
        total,
        passed,
        failed,
        output,
        elapsed_ms: Date.now() - start
      }
    } catch (error) {
      const err = error as { stdout?: string; message?: string }
      return {
        ok: false,
        total: 0,
        passed: 0,
        failed: 1,
        output: err.stdout || err.message || '',
        elapsed_ms: Date.now() - start
      }
    }
  }

  private parse_ctest_output(output: string): { total: number; passed: number; failed: number } {
    const match = output.match(/(\d+)\/?(?:\d+)?\s*Test.*#\d+:|Tests\s+passed.*(\d+)\s+total/i)
    if (match) {
      return { total: parseInt(match[1]) || 0, passed: parseInt(match[1]) || 0, failed: 0 }
    }
    return { total: 0, passed: 0, failed: 0 }
  }
}
