#!/usr/bin/env python3
"""Check the actual linked Chinese font assets; run with the ESP-IDF Python.

Usage: python firmware/tests/transcript_glyph_test.py firmware/build/device_lab.elf
This checks glyph coverage, not physical display output or STT accuracy.
"""
import sys

from elftools.elf.elffile import ELFFile


def font_data(elf, name):
    symbol = next(s for s in elf.get_section_by_name(".symtab").iter_symbols()
                  if s.name == name)
    section = elf.get_section(symbol["st_shndx"])
    offset = symbol["st_value"] - section["sh_addr"]
    return section.data()[offset:offset + symbol["st_size"]]


def has_glyph(data, code):
    # M5GFX U8g2 Unicode LUT: cumulative block offsets, then variable records.
    position = 23 + int.from_bytes(data[21:23], "big")
    lookup = position
    while True:
        position += int.from_bytes(data[lookup:lookup + 2], "big")
        end = int.from_bytes(data[lookup + 2:lookup + 4], "big")
        lookup += 4
        if end >= code:
            break
    while int.from_bytes(data[position:position + 2], "big"):
        if int.from_bytes(data[position:position + 2], "big") == code:
            return True
        size = data[position + 2]
        assert size > 3, "invalid glyph record"
        position += size
    return False


with open(sys.argv[1], "rb") as handle:
    elf = ELFFile(handle)
    cn = font_data(elf, "lgfx_efont_cn_16")
    tw = font_data(elf, "lgfx_efont_tw_16")

# Fallback assumes identical line height and baseline. Verify compiled assets.
assert cn[10:13] == tw[10:13], "Chinese font line metrics differ"
for character in "这是录音测试现在电這是錄音測試現在電哈喽你好正在检查已完成依赖不可用":
    assert has_glyph(cn, ord(character)) or has_glyph(tw, ord(character)), \
        f"missing test glyph U+{ord(character):04X}"
for character in "現電":
    assert not has_glyph(cn, ord(character)), "fallback probe no longer needs TW"
    assert has_glyph(tw, ord(character)), "traditional fallback glyph missing"
print("Transcript glyph coverage PASS (linked CN + TW, matching line metrics)")
