const { runAudit } = require("../lib/audit");

module.exports = async function audit(_args, flags) {
  const rootDir = process.cwd();
  const report = runAudit(rootDir);

  if (flags.json) {
    console.log(JSON.stringify(report, null, 2));
    if (!report.pass) process.exit(report.exit_code);
    return;
  }

  console.log("\n## CapInt Audit (read-only)\n");
  console.log(`Result: ${report.pass ? "PASS" : "FAIL"}`);
  console.log(`Doctor: ${report.doctor_pass ? "pass" : "fail"}`);
  console.log(`Findings: ${report.summary.issues} issues, ${report.summary.warnings} warnings, ${report.summary.info} info\n`);

  if (report.findings.length) {
    for (const f of report.findings) {
      console.log(`  [${f.level}] ${f.message}`);
    }
    console.log("");
  }

  if (report.recommendations.length) {
    console.log("Recommendations:");
    for (const r of report.recommendations) console.log(`  - ${r}`);
    console.log("");
  }

  if (!report.pass) process.exit(report.exit_code);
};
