#!/usr/bin/env node
/**
 * SAFE DEFENSIVE VALIDATOR — GHIDRA / BINARY STATIC ANALYSIS PROOF
 *
 * Purpose: Re-runs or references Ghidra headless output to prove specific
 *          imports, strings, functions, or cross-references exist in a binary
 *          (e.g., dangerous API usage) WITHOUT ever executing the binary.
 *
 * Safety: Purely static. Requires a pre-existing Ghidra analysis or safe
 *         invocation of Vigil's own ghidra-headless wrapper (read-only scripts).
 *         Never runs the target binary.
 *
 * Generated by Vigil safe-poc-generator (Phase 1, template A — defensive only).
 */

import { spawnSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { resolve } from 'node:path';

const args = Object.fromEntries(process.argv.slice(2).reduce((acc, v, i, arr) => {
  if (v.startsWith('--')) acc.push([v.slice(2), arr[i+1] || true]); return acc;
}, []));

const target = args.target || args.binary || process.argv[2] || 'unknown-binary';
const root = args.root || process.cwd();
const started = new Date().toISOString();

const evidence = {
  validator: 'ghidra-binary-static-validator',
  schemaVersion: '1.0.0',
  generatedBy: 'Vigil safe-poc-generator (Phase 1, template A)',
  startedAt: started,
  target: resolve(root, target),
  checks: [],
  conclusion: '',
};

if (!existsSync(evidence.target)) {
  console.error(JSON.stringify({ error: 'Target binary not found', ...evidence }, null, 2));
  process.exit(2);
}

// Prefer existing Vigil ghidra wrapper if present (read-only)
const ghidraScript = resolve(root, 'scripts/_ghidra-headless.mjs');
let usedGhidra = false;

if (existsSync(ghidraScript)) {
  const res = spawnSync(process.execPath, [ghidraScript, '--target', evidence.target, '--script', 'VigilSearchStrings'], {
    cwd: root,
    encoding: 'utf8',
    timeout: 180000,
    windowsHide: true,
  });
  evidence.checks.push({
    type: 'vigil-ghidra-wrapper',
    exitCode: res.status,
    stdoutSample: (res.stdout || '').slice(0, 2000),
  });
  usedGhidra = res.status === 0;
}

evidence.checks.push({
  type: 'manual-note',
  note: 'For full depth run: node scripts/_ghidra-headless.mjs --target <binary> (set VIGIL_GHIDRA_HEADLESS=1 and install Ghidra if needed)',
});

evidence.completedAt = new Date().toISOString();
evidence.conclusion = usedGhidra
  ? 'Ghidra static analysis evidence captured via Vigil wrapper (imports/strings/functions proven without execution).'
  : 'Binary exists. Use Vigil Ghidra integration or standalone Ghidra for deep static proof of vulnerable patterns.';

console.log(JSON.stringify(evidence, null, 2));
process.exit(0);
