/**
 * OG image generation via satori + resvg.
 * Returns PNG buffer for /api/og/* endpoints.
 *
 * Card layout: 1200×630 with vreaudigital brand strip top, big title, accent line,
 * primary metric large, sub-metric small, "vreaudigital.ro" footer.
 */
import satori from 'satori';
import { Resvg } from '@resvg/resvg-js';
import { readFile } from 'node:fs/promises';
import path from 'node:path';

let cachedFonts: Awaited<ReturnType<typeof loadFonts>> | null = null;

async function loadFonts() {
  // Load Plus Jakarta Sans + Inter directly from node_modules (bundled with @fontsource).
  const root = process.cwd();
  const tryPaths = (pkgPath: string) => [
    path.join(root, 'node_modules', pkgPath),
  ];

  async function read(p: string): Promise<Buffer | null> {
    for (const candidate of tryPaths(p)) {
      try { return await readFile(candidate); } catch { /* try next */ }
    }
    return null;
  }

  const jakartaBold = await read('@fontsource/plus-jakarta-sans/files/plus-jakarta-sans-latin-700-normal.woff');
  const jakartaExtra = await read('@fontsource/plus-jakarta-sans/files/plus-jakarta-sans-latin-800-normal.woff');
  const interReg = await read('@fontsource/inter/files/inter-latin-400-normal.woff');
  const interMed = await read('@fontsource/inter/files/inter-latin-500-normal.woff');

  const fonts: any[] = [];
  if (interReg) fonts.push({ name: 'Inter', data: interReg, weight: 400, style: 'normal' });
  if (interMed) fonts.push({ name: 'Inter', data: interMed, weight: 500, style: 'normal' });
  if (jakartaBold) fonts.push({ name: 'Plus Jakarta Sans', data: jakartaBold, weight: 700, style: 'normal' });
  if (jakartaExtra) fonts.push({ name: 'Plus Jakarta Sans', data: jakartaExtra, weight: 800, style: 'normal' });
  return fonts;
}

interface OgCardProps {
  kicker: string;
  title: string;
  primary: string;
  secondary?: string;
  badge?: string;
  badgeTone?: 'risk' | 'warn' | 'ok' | 'info';
}

async function renderCard(props: OgCardProps): Promise<Buffer> {
  if (!cachedFonts) cachedFonts = await loadFonts();
  if (!cachedFonts || cachedFonts.length === 0) {
    throw new Error('No fonts available for OG image generation');
  }

  const badgeColors: Record<string, { bg: string; fg: string }> = {
    risk: { bg: '#FEF2F2', fg: '#B91C1C' },
    warn: { bg: '#FEF3C7', fg: '#B45309' },
    ok:   { bg: '#D1FAE5', fg: '#047857' },
    info: { bg: '#DBEAFE', fg: '#1D4ED8' },
  };
  const bColor = props.badgeTone ? badgeColors[props.badgeTone] : badgeColors.info;

  const tree: any = {
    type: 'div',
    props: {
      style: {
        width: '1200px',
        height: '630px',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'space-between',
        background: 'linear-gradient(135deg, #FAFBFC 0%, #F1F5F9 100%)',
        padding: '60px 70px',
        fontFamily: 'Inter, sans-serif',
        position: 'relative',
      },
      children: [
        // Top brand
        {
          type: 'div',
          props: {
            style: {
              display: 'flex',
              alignItems: 'center',
              gap: '14px',
              fontSize: '20px',
              fontWeight: 700,
              fontFamily: 'Plus Jakarta Sans',
            },
            children: [
              { type: 'span', props: { style: { color: '#0F172A' }, children: 'vreau' } },
              { type: 'span', props: { style: { color: '#2563EB' }, children: 'digital' } },
              { type: 'span', props: { style: { color: '#94A3B8', fontSize: '15px', fontWeight: 500, marginLeft: '6px' }, children: '· transparență achiziții publice' } },
            ],
          },
        },

        // Middle content
        {
          type: 'div',
          props: {
            style: { display: 'flex', flexDirection: 'column', gap: '24px' },
            children: [
              // Kicker
              props.kicker ? {
                type: 'div',
                props: {
                  style: {
                    fontFamily: 'Plus Jakarta Sans',
                    fontWeight: 700,
                    fontSize: '14px',
                    color: '#2563EB',
                    textTransform: 'uppercase',
                    letterSpacing: '0.08em',
                  },
                  children: props.kicker,
                },
              } : null,

              // Title
              {
                type: 'div',
                props: {
                  style: {
                    fontFamily: 'Plus Jakarta Sans',
                    fontWeight: 800,
                    fontSize: '54px',
                    color: '#0F172A',
                    lineHeight: 1.1,
                    letterSpacing: '-0.02em',
                    maxWidth: '1000px',
                  },
                  children: props.title.length > 90 ? props.title.slice(0, 88) + '…' : props.title,
                },
              },

              // Accent line
              {
                type: 'div',
                props: {
                  style: { width: '70px', height: '4px', background: '#2563EB', borderRadius: '4px' },
                },
              },

              // Primary metric
              {
                type: 'div',
                props: {
                  style: { display: 'flex', alignItems: 'baseline', gap: '20px' },
                  children: [
                    {
                      type: 'div',
                      props: {
                        style: {
                          fontFamily: 'Plus Jakarta Sans',
                          fontWeight: 800,
                          fontSize: '64px',
                          color: '#1D4ED8',
                          lineHeight: 1,
                        },
                        children: props.primary,
                      },
                    },
                    props.badge ? {
                      type: 'div',
                      props: {
                        style: {
                          background: bColor.bg,
                          color: bColor.fg,
                          fontSize: '15px',
                          fontWeight: 700,
                          padding: '8px 14px',
                          borderRadius: '999px',
                          textTransform: 'uppercase',
                          letterSpacing: '0.05em',
                        },
                        children: props.badge,
                      },
                    } : null,
                  ].filter(Boolean),
                },
              },

              // Secondary
              props.secondary ? {
                type: 'div',
                props: {
                  style: {
                    fontFamily: 'Inter',
                    fontSize: '24px',
                    color: '#475569',
                    maxWidth: '1000px',
                    lineHeight: 1.4,
                  },
                  children: props.secondary.length > 120 ? props.secondary.slice(0, 118) + '…' : props.secondary,
                },
              } : null,
            ].filter(Boolean),
          },
        },

        // Footer
        {
          type: 'div',
          props: {
            style: {
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              fontSize: '15px',
              color: '#64748B',
            },
            children: [
              { type: 'span', props: { style: { fontFamily: 'Plus Jakarta Sans', fontWeight: 700 }, children: 'vreaudigital.ro' } },
              { type: 'span', props: { style: { color: '#94A3B8' }, children: 'date din SEAP · TED · datagov · CC-BY 4.0' } },
            ],
          },
        },
      ],
    },
  };

  const svg = await satori(tree, {
    width: 1200,
    height: 630,
    fonts: cachedFonts,
    embedFont: true,
  });

  const resvg = new Resvg(svg, {
    background: 'rgba(255, 255, 255, 1)',
    fitTo: { mode: 'width', value: 1200 },
  });
  return resvg.render().asPng();
}

export async function ogRecipeImage(opts: {
  title: string;
  count: number;
  primaryRow?: { name: string; metric: string; tone?: 'risk' | 'warn' | 'ok' };
}): Promise<Buffer> {
  return renderCard({
    kicker: 'Rețetă investigativă',
    title: opts.title,
    primary: `${opts.count} rezultate`,
    secondary: opts.primaryRow ? `Cel mai mare: ${opts.primaryRow.name} — ${opts.primaryRow.metric}` : undefined,
    badge: opts.primaryRow?.tone === 'risk' ? 'risc ridicat' : opts.primaryRow?.tone === 'warn' ? 'verifică' : undefined,
    badgeTone: opts.primaryRow?.tone,
  });
}

export async function ogProfileImage(opts: {
  kind: 'firma' | 'autoritate';
  name: string;
  cui: string;
  totalValue: string; // already formatted RON
  contracts: number;
  highlight?: string;
}): Promise<Buffer> {
  return renderCard({
    kicker: opts.kind === 'firma' ? 'Profil furnizor' : 'Profil autoritate contractantă',
    title: opts.name,
    primary: `${opts.totalValue} RON`,
    secondary: `${opts.contracts} anunțuri · CUI ${opts.cui}${opts.highlight ? ' · ' + opts.highlight : ''}`,
    badge: undefined,
  });
}
