#!/usr/bin/env node
import { writeFile } from "node:fs/promises";

import {
  buildReport,
  formatCheckSummary,
  renderMarkdown,
  repoRoot
} from "./src/dev-evidence-blocker-aggregator.mjs";
import { ensureNotRepoReportsPath, tempReportPath } from "./src/report-paths.mjs";

function hasFlag(name) {
  return process.argv.includes(name);
}

try {
  const report = await buildReport();
  const reportFlagIndex = process.argv.indexOf("--report");
  const markdownFlagIndex = process.argv.indexOf("--markdown-report");
  const wroteReports = reportFlagIndex !== -1 || markdownFlagIndex !== -1;
  const jsonPath = reportFlagIndex !== -1
    ? ensureNotRepoReportsPath(repoRoot, process.argv[reportFlagIndex + 1], "--report")
    : ensureNotRepoReportsPath(repoRoot, tempReportPath("dev-m5-gate-aggregator-v2.json"), "--report");
  const markdownPath = markdownFlagIndex !== -1
    ? ensureNotRepoReportsPath(repoRoot, process.argv[markdownFlagIndex + 1], "--markdown-report")
    : ensureNotRepoReportsPath(repoRoot, tempReportPath("dev-m5-gate-aggregator-v2.md"), "--markdown-report");

  if (wroteReports) {
    await writeFile(jsonPath, `${JSON.stringify(report, null, 2)}\n`);
    await writeFile(markdownPath, renderMarkdown(report));
  }

  if (hasFlag("--check")) {
    process.stdout.write(`${JSON.stringify(formatCheckSummary(report))}\n`);
  } else if (hasFlag("--markdown")) {
    process.stdout.write(renderMarkdown(report));
  } else if (wroteReports) {
    process.stdout.write(`${JSON.stringify({
      ...formatCheckSummary(report),
      wrote: [
        jsonPath,
        markdownPath
      ]
    })}\n`);
  } else {
    process.stdout.write(`${JSON.stringify(report, null, hasFlag("--pretty") ? 2 : 0)}\n`);
  }
} catch (error) {
  const message = error instanceof Error ? error.message : String(error);
  process.stderr.write(`${JSON.stringify({ ok: false, error: message })}\n`);
  process.exitCode = 1;
}
