import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";

const repoRoot = process.cwd();
const defaultPackages = ["adminfront", "devfront", "orgfront"];
const packages = process.argv.slice(2);
const targetPackages = packages.length > 0 ? packages : defaultPackages;

function formatPct(value) {
  return typeof value === "number" ? `${value.toFixed(2)}%` : "n/a";
}

async function readCoverageSummary(packageName) {
  const summaryPath = path.join(
    repoRoot,
    packageName,
    "coverage",
    "coverage-summary.json",
  );
  const raw = await readFile(summaryPath, "utf8");
  const summary = JSON.parse(raw);
  const total = summary.total;

  return {
    package: packageName,
    statements: total.statements.pct,
    branches: total.branches.pct,
    functions: total.functions.pct,
    lines: total.lines.pct,
    summaryPath: path.relative(repoRoot, summaryPath),
    htmlPath: `${packageName}/coverage/index.html`,
    lcovPath: `${packageName}/coverage/lcov.info`,
  };
}

function renderMarkdown(rows) {
  const lines = [
    "# Vitest Coverage Summary",
    "",
    "| Package | Statements | Branches | Functions | Lines | HTML Report | LCOV |",
    "| --- | ---: | ---: | ---: | ---: | --- | --- |",
  ];

  for (const row of rows) {
    lines.push(
      [
        `| ${row.package}`,
        formatPct(row.statements),
        formatPct(row.branches),
        formatPct(row.functions),
        formatPct(row.lines),
        row.htmlPath,
        `${row.package}/coverage/lcov.info |`,
      ].join(" | "),
    );
  }

  lines.push(
    "",
    "Coverage includes each app's `src` tree and imported/covered files under `common`.",
    "",
  );

  return lines.join("\n");
}

const rows = [];
for (const packageName of targetPackages) {
  rows.push(await readCoverageSummary(packageName));
}

const reportsDir = path.join(repoRoot, "reports");
await mkdir(reportsDir, { recursive: true });
await writeFile(
  path.join(reportsDir, "vitest-coverage-summary.json"),
  `${JSON.stringify({ packages: rows }, null, 2)}\n`,
);
await writeFile(
  path.join(reportsDir, "vitest-coverage-summary.md"),
  renderMarkdown(rows),
);

console.log(renderMarkdown(rows));
