#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
from fontTools.ttLib import TTFont

def modify_font_metrics(input_font_path, output_font_path, scale=0.1):
    font = TTFont(input_font_path)

    hhea = font['hhea']
    original_ascender = hhea.ascent
    original_descender = hhea.descent
    original_lineGap = hhea.lineGap

    if original_ascender > 0:
        my_ascender = original_ascender
    else:
        my_ascender = 0

    if original_descender > 0:
        my_descender = original_descender
    else:
        my_descender = 0

    new_line_gap = int(scale * (original_ascender + original_descender))
    hhea.lineGap = new_line_gap

    os2 = font['OS/2']

    # Here: Update the fsSelection field to disable USE_TYPO_METRICS
    fsSelection = os2.fsSelection
    os2.fsSelection = fsSelection & ~(1 << 7)  # Clear bit 7 (128)

    os2.sTypoLineGap = new_line_gap

    name_table = font['name']
    scale_suffix = f" gap+{int(scale * 100)}%"

    for name_record in name_table.names:
        # Change name inside: "Font Family Name", "Full Font Name", "PostScript Name"
        if name_record.nameID in [1, 4, 6]:
            new_name = name_record.toUnicode() + scale_suffix
            name_record.string = new_name.encode(name_record.getEncoding())

    font.save(output_font_path)

# Sample
input_font_path = "./IBMPlexMono-Regular.ttf"
output_font_path = "./IBMPlexMono-Regular-modified7.ttf"
modify_font_metrics(input_font_path, output_font_path, scale=0.5)
