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.
 */
let cachedFonts: any[] | null = null;
export async function getOgFonts() {
  if (cachedFonts) return cachedFonts;
  const boldFontPath = join(process.cwd(), 'public/fonts/Inter-Bold.woff');
  const regularFontPath = join(process.cwd(), 'public/fonts/Inter-Regular.woff');

  try {
    console.log(`[OG] Loading fonts: bold=${boldFontPath}, regular=${regularFontPath}`);
    const boldFontBuffer = readFileSync(boldFontPath);
    const regularFontBuffer = readFileSync(regularFontPath);
    
    // Satori strictly requires an ArrayBuffer.
    const boldFont = boldFontBuffer.buffer.slice(
      boldFontBuffer.byteOffset,
      boldFontBuffer.byteOffset + boldFontBuffer.byteLength,
    );
    const regularFont = regularFontBuffer.buffer.slice(
      regularFontBuffer.byteOffset,
      regularFontBuffer.byteOffset + regularFontBuffer.byteLength,
    );

    console.log(
      `[OG] Fonts loaded successfully (${boldFont.byteLength} and ${regularFont.byteLength} bytes)`,
    );

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

let cachedBackground: string | null = null;
export function getOgBackground() {
  if (cachedBackground) return cachedBackground;
  try {
    const bgPath = join(process.cwd(), 'public/assets/photos/Etib_E-tib_Tiefbau_Guben_Netzanbindung_Energie-100.jpg');
    const bgBase64 = readFileSync(bgPath, 'base64');
    cachedBackground = `data:image/jpeg;base64,${bgBase64}`;
    return cachedBackground;
  } catch (err) {
    console.error('[OG] Failed to load background', err);
    return undefined;
  }
}

let cachedLogo: string | null = null;
export function getOgLogo() {
  if (cachedLogo) return cachedLogo;
  try {
    const logoPath = join(process.cwd(), 'public/assets/logo-white.png');
    const logoBase64 = readFileSync(logoPath, 'base64');
    cachedLogo = `data:image/png;base64,${logoBase64}`;
    return cachedLogo;
  } catch (err) {
    console.error('[OG] Failed to load logo', err);
    return undefined;
  }
}

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