import { readFileSync, writeFileSync, existsSync, appendFileSync } from "fs";

const packages = [
  { dir: "apps/api", name: "api" },
  { dir: "packages/shared", name: "shared" },
  { dir: "packages/agent-adapters", name: "agent-adapters" },
];

const lines = ["## Test Coverage Report", ""];
const rows = [];

for (const pkg of packages) {
  const file = `${pkg.dir}/coverage/coverage-summary.json`;
  if (!existsSync(file)) continue;

  const summary = JSON.parse(readFileSync(file, "utf8")).total;

  const format = (data) => {
    const pct = data.pct;
    const icon = pct >= 80 ? "🟢" : pct >= 60 ? "🟡" : "🔴";
    return `${icon} ${pct}%`;
  };

  rows.push(
    `| ${pkg.name} | ${format(summary.lines)} | ${format(summary.branches)} | ${format(summary.functions)} | ${format(summary.statements)} |`,
  );
}

if (rows.length > 0) {
  lines.push(
    "| Package | Lines | Branches | Functions | Statements |",
    "|---------|-------|----------|-----------|------------|",
    ...rows,
    "",
  );
} else {
  lines.push("_No coverage data generated._", "");
}

lines.push("<sub>Generated by CI — test coverage via vitest + v8</sub>", "");

const report = lines.join("\n");

// Write to file for PR comment step
writeFileSync("coverage-report.md", report);

// Write to GitHub step summary if available
if (process.env.GITHUB_STEP_SUMMARY) {
  appendFileSync(process.env.GITHUB_STEP_SUMMARY, report);
}

console.log(report);
