import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Objects;

public class FontCrashReproducer {
  public static void main(String[] args) throws InterruptedException {
    var t1 = Thread.ofVirtual().start(() -> handle("oh"));
    var t2 = Thread.ofVirtual().start(() -> handle("no"));
    t1.join();
    t2.join();
    System.out.println("Failed to crash as expected");
  }

  public static final Font font = createFont();

  public static Font createFont() {
    // Loading a font which happens to exist in the docker image for simplicity of the reproducer
    try (var fontFile = new FileInputStream(Paths.get("/usr/share/fonts/google-noto-vf/NotoSansSinhala-VF.ttf").toFile())) {
      var font = Font.createFont(Font.TRUETYPE_FONT, Objects.requireNonNull(fontFile));
      var map = new HashMap<TextAttribute, Object>();
      map.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); // Disabling Kerning avoids the bug
      // But issue is not specific to KERNING. LIGATURES would also cause the crash.
      // However, sending an empty map would avoid the crash.
     return font.deriveFont(map);
    } catch (FontFormatException | IOException e) {
      throw new IllegalStateException("Failed to load font resource", e);
    }
  }

  public static void handle(String text) {
    var img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
    var canvas = img.createGraphics();
    canvas.setFont(font);
    var fontMetrics = canvas.getFontMetrics();
    fontMetrics.stringWidth(text);
  }
}