const WEIGHT_TO_GRAMS: Record<string, number> = {
  g: 1, gram: 1, grams: 1,
  kg: 1000, kilogram: 1000, kilograms: 1000,
  oz: 28.3495, ounce: 28.3495, ounces: 28.3495,
  lb: 453.592, lbs: 453.592, pound: 453.592, pounds: 453.592,
};

// Volume converted via a 1ml ≈ 1g water-density approximation — a real
// simplification (oil is ~0.92g/ml, honey ~1.4g/ml) but the best available
// without a per-ingredient density table, and still far better than
// skipping every cup/tbsp/tsp-measured ingredient's USDA lookup entirely.
const VOLUME_TO_ML: Record<string, number> = {
  ml: 1, milliliter: 1, milliliters: 1, millilitre: 1, millilitres: 1,
  l: 1000, liter: 1000, liters: 1000, litre: 1000, litres: 1000,
  tsp: 4.92892, teaspoon: 4.92892, teaspoons: 4.92892,
  tbsp: 14.7868, tablespoon: 14.7868, tablespoons: 14.7868,
  cup: 236.588, cups: 236.588,
  "fl oz": 29.5735, "fl. oz": 29.5735, floz: 29.5735,
  pt: 473.176, pint: 473.176, pints: 473.176,
  qt: 946.353, quart: 946.353, quarts: 946.353,
  gal: 3785.41, gallon: 3785.41, gallons: 3785.41,
};

function normalize(unit: string): string {
  return unit.trim().toLowerCase().replace(/\.$/, "");
}

/** Best-effort quantity+unit -> grams, for feeding a USDA per-100g lookup.
 * Returns null for count-based units ("2 cloves", "1 can") or missing
 * quantity/unit — those ingredients fall back to AI estimation instead. */
export function estimateGrams(quantity: string | number | null | undefined, unit: string | null | undefined): number | null {
  if (quantity == null || !unit) return null;
  const value = typeof quantity === "number" ? quantity : parseFloat(quantity);
  if (!isFinite(value) || value <= 0) return null;

  const key = normalize(unit);
  if (key in WEIGHT_TO_GRAMS) return value * WEIGHT_TO_GRAMS[key]!;
  if (key in VOLUME_TO_ML) return value * VOLUME_TO_ML[key]!;
  return null;
}
