import { readFileSync } from "fs";
import { join } from "path";

/**
 * Loads the Inter fonts for use in Satori (Next.js OG Image generation).
 * Since we are using runtime = 'nodejs', we can read them from the filesystem.
 */
export async function getOgFonts() {
  // Use relative path from process.cwd() which usually is the monorepo root or apps/web
  // We try both to be safe during different execution contexts (dev vs build vs runtime)
  const pathsToTry = [
    join(process.cwd(), "apps/web/public/fonts"),
    join(process.cwd(), "public/fonts"),
  ];

  let boldFontPath = "";
  let regularFontPath = "";

  for (const basePath of pathsToTry) {
    const b = join(basePath, "Inter-Bold.woff");
    const r = join(basePath, "Inter-Regular.woff");
    try {
      if (readFileSync(b) && readFileSync(r)) {
        boldFontPath = b;
        regularFontPath = r;
        break;
      }
    } catch (e) {
      continue;
    }
  }

  if (!boldFontPath || !regularFontPath) {
    console.error(
      `[OG] Could not find fonts in either ${pathsToTry.join(" or ")}`,
    );
    return [];
  }

  try {
    console.log(
      `[OG] Loading fonts: bold=${boldFontPath}, regular=${regularFontPath}`,
    );
    const boldFont = readFileSync(boldFontPath);
    const regularFont = readFileSync(regularFontPath);
    console.log(
      `[OG] Fonts loaded successfully (${boldFont.length} and ${regularFont.length} bytes)`,
    );

    return [
      {
        name: "Inter",
        data: boldFont,
        weight: 700 as const,
        style: "normal" as const,
      },
      {
        name: "Inter",
        data: regularFont,
        weight: 400 as const,
        style: "normal" as const,
      },
    ];
  } catch (error) {
    console.error(`[OG] Failed to load fonts:`, error);
    return [];
  }
}

/**
 * Common configuration for OG images
 */
export const OG_IMAGE_SIZE = {
  width: 1200,
  height: 630,
};
