import fs from "node:fs";
import path from "node:path";

export const REPORT_THEME = {
  primary: "1f4e78",
  lightBg: "f2f6fb",
  border: "d1d5db",
  text: "111827",
  mutedText: "6b7280",
  white: "ffffff",
  page: {
    size: "A4" as const,
    margin: 50,
  },
};

const LOGO_CANDIDATE_PATHS = [
  path.resolve(process.cwd(), "../frontend/src/assets/M_E Logo.png"),
  path.resolve(process.cwd(), "../frontend/public/logo.png"),
];

export function loadSystemLogo(): Buffer | null {
  for (const p of LOGO_CANDIDATE_PATHS) {
    if (fs.existsSync(p)) {
      try {
        return fs.readFileSync(p);
      } catch {
        // ignore logo read failures and continue
      }
    }
  }
  return null;
}

export function detectImageType(buf: Buffer): "png" | "jpg" {
  const isPng = buf.length > 8 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47;
  return isPng ? "png" : "jpg";
}

export function formatReportDate(value: string): string {
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return value;
  return d.toISOString().slice(0, 10);
}

export function toPercent(part: number, total: number): number {
  if (!total) return 0;
  // Round to nearest integer for clean display (e.g., 100% not 99.97%)
  return Math.round((part / total) * 100);
}

