// SPEC: PJ2026-010606 GitHub入口 draft-2026-06-25-gh-split
// Moved mechanically from scripts/src/gh.ts:4686-5550.

import { bodySha, preview, previewLines } from "./auth-and-safety";
import type { GitHubComment } from "./types";

export function commentSummary(comment: GitHubComment): Record<string, unknown> {
  const body = comment.body ?? "";
  return {
    id: comment.id,
    body,
    url: comment.html_url,
    author: comment.user?.login ?? null,
    createdAt: comment.created_at ?? null,
    updatedAt: comment.updated_at ?? null,
    bodyChars: body.length,
    bodySha: bodySha(body),
    bodyOmitted: false,
    fullBodyIncluded: true,
  };
}

export function compactCommentSummary(comment: GitHubComment): Record<string, unknown> {
  const body = comment.body ?? "";
  return {
    id: comment.id,
    url: comment.html_url,
    author: comment.user?.login ?? null,
    createdAt: comment.created_at ?? null,
    updatedAt: comment.updated_at ?? null,
    bodyChars: body.length,
    bodySha: bodySha(body),
    bodyPreview: preview(body),
    bodyPreviewLines: previewLines(body, 4),
    bodyOmitted: true,
    fullBodyIncluded: false,
  };
}

export function compactIssueViewCommentSummary(comment: GitHubComment): Record<string, unknown> {
  const body = comment.body ?? "";
  return {
    id: comment.id,
    url: comment.html_url,
    author: comment.user?.login ?? null,
    createdAt: comment.created_at ?? null,
    updatedAt: comment.updated_at ?? null,
    bodyChars: body.length,
    bodySha: bodySha(body),
    bodyPreview: ghShort(preview(body).replace(/\s+/gu, " "), 200),
    bodyOmitted: true,
    fullBodyIncluded: false,
  };
}

export function ghTable(headers: string[], rows: string[][]): string {
  const normalizedRows = rows.map((row) => headers.map((_, index) => row[index] ?? ""));
  const widths = headers.map((header, index) => Math.max(header.length, ...normalizedRows.map((row) => row[index].length)));
  return [
    headers.map((header, index) => header.padEnd(widths[index])).join("  ").trimEnd(),
    ...normalizedRows.map((row) => row.map((cell, index) => cell.padEnd(widths[index])).join("  ").trimEnd()),
  ].join("\n");
}

export function ghText(value: unknown): string {
  if (value === null || value === undefined || value === "") return "-";
  if (typeof value === "string") return value;
  if (typeof value === "number" || typeof value === "boolean") return String(value);
  return JSON.stringify(value);
}

export function ghShort(value: string, maxLength: number): string {
  if (value.length <= maxLength) return value;
  if (maxLength <= 1) return value.slice(0, maxLength);
  return `${value.slice(0, maxLength - 1)}~`;
}
