#!/usr/bin/env bash
# Regenerate the CJK subsets used by all child-facing LVGL pages.
# Optional argument: a local NotoSansCJKsc-Regular.otf file.
set -euo pipefail

project_root="$(cd "$(dirname "$0")/.." && pwd)"
if [[ $# -ge 1 ]]; then
    font_file="$1"
else
    cache_dir="$project_root/build/font-cache"
    mkdir -p "$cache_dir"
    font_file="$cache_dir/NotoSansCJKsc-Regular.otf"
    if [[ ! -s "$font_file" ]]; then
        curl -L --fail --silent --show-error \
            https://raw.githubusercontent.com/notofonts/noto-cjk/main/Sans/OTF/SimplifiedChinese/NotoSansCJKsc-Regular.otf \
            -o "$font_file"
    fi
fi

font_dir="$project_root/src/display/ui/fonts"
symbols="$(python3 - "$project_root/src/display/ui" <<'PY'
from pathlib import Path
import sys
chars = set()
for path in Path(sys.argv[1]).rglob('*'):
    if path.suffix in ('.cpp', '.h'):
        chars.update(c for c in path.read_text() if '\u3400' <= c <= '\u9fff')
print(''.join(sorted(chars)) + '，。：！·✓○…')
PY
)"
lv_font_conv --font "$font_file" --range 0x20-0x7E \
    --symbols "$symbols" \
    --size 22 --bpp 4 --no-compress --format lvgl --lv-include lvgl.h \
    -o "$font_dir/lv_font_home_22.c"
lv_font_conv --font "$font_file" --range 0x20-0x7E --symbols "$symbols" \
    --size 32 --bpp 4 --no-compress --format lvgl --lv-include lvgl.h \
    -o "$font_dir/lv_font_home_32.c"
lv_font_conv --font "$font_file" --range 0x20-0x7E --symbols "$symbols" \
    --size 44 --bpp 4 --no-compress --format lvgl --lv-include lvgl.h \
    -o "$font_dir/lv_font_home_44.c"
