/**
 * PR Reporter Utilities
 *
 * Handles building and posting consolidated PR comments from multiple reporters.
 */

import type { CIContext, ReportItem } from "../reporters/types";
import { postPRComment as postGitHubPRComment, GITHUB_REPO_OWNER, GITHUB_REPO_NAME } from "./github-api";

/**
 * Build a consolidated markdown comment from report items
 */
export function buildMarkdownComment(
  items: ReportItem[],
  failures: string[] = [],
): string {
  // Sort by priority (lower = higher in comment)
  const sorted = [...items].sort((a, b) => a.priority - b.priority);

  const sections = sorted.map((item) => {
    return `### ${item.title}\n\n${item.content}`;
  });

  // Add warning section if there were failures
  if (failures.length > 0) {
    sections.push(
      `### Warning\n\nFailed to load ${failures.length} report artifact(s): ${failures.join(", ")}`,
    );
  }

  const header = "## PR Release Summary\n";
  const footer =
    `\n---\n*Auto-generated by [Kumo CI](https://github.com/${GITHUB_REPO_OWNER}/${GITHUB_REPO_NAME})*`;

  return `${header}\n${sections.join("\n\n")}\n${footer}`;
}

/**
 * Post a new comment to the PR
 */
export async function postPRComment(
  context: CIContext,
  body: string,
): Promise<void> {
  const { prNumber, apiToken } = context;

  const missing: string[] = [];
  if (!prNumber) missing.push("prNumber (GITHUB_PR_NUMBER)");
  if (!apiToken) missing.push("apiToken (GITHUB_TOKEN)");

  if (missing.length > 0) {
    console.log(`  Missing required variables: ${missing.join(", ")}`);
    return;
  }

  await postGitHubPRComment(apiToken, Number(prNumber), body);

  console.log(`  Posted PR comment to #${prNumber}`);
}
