import { fromBuffer } from "@capsizecss/unpack";
import { renderFontFace, renderFontSrc } from "./utils.js";
const metricCache = {};
function filterRequiredMetrics({
  ascent,
  descent,
  lineGap,
  unitsPerEm,
  xWidthAvg
}) {
  return {
    ascent,
    descent,
    lineGap,
    unitsPerEm,
    xWidthAvg
  };
}
async function readMetrics(family, buffer) {
  const metrics = await fromBuffer(buffer);
  metricCache[family] = filterRequiredMetrics(metrics);
  return metricCache[family];
}
function toPercentage(value, fractionDigits = 4) {
  const percentage = value * 100;
  return `${+percentage.toFixed(fractionDigits)}%`;
}
function generateFallbackFontFace({
  metrics,
  fallbackMetrics,
  name: fallbackName,
  font: fallbackFontName,
  properties
}) {
  const preferredFontXAvgRatio = metrics.xWidthAvg / metrics.unitsPerEm;
  const fallbackFontXAvgRatio = fallbackMetrics.xWidthAvg / fallbackMetrics.unitsPerEm;
  const sizeAdjust = preferredFontXAvgRatio / fallbackFontXAvgRatio;
  const adjustedEmSquare = metrics.unitsPerEm * sizeAdjust;
  const ascentOverride = metrics.ascent / adjustedEmSquare;
  const descentOverride = Math.abs(metrics.descent) / adjustedEmSquare;
  const lineGapOverride = metrics.lineGap / adjustedEmSquare;
  return renderFontFace({
    "font-family": fallbackName,
    src: renderFontSrc([{ name: fallbackFontName }]),
    "size-adjust": toPercentage(sizeAdjust),
    "ascent-override": toPercentage(ascentOverride),
    "descent-override": toPercentage(descentOverride),
    "line-gap-override": toPercentage(lineGapOverride),
    ...properties
  });
}
export {
  generateFallbackFontFace,
  readMetrics
};
