#!/usr/bin/env bash

# Lists installed font families, split by what they are usable for.
#
# Two separate questions get asked of fonts here, and they have different
# answers:
#
#   interface   proportional families suitable for reading UI text
#   monospace   fixed-pitch families
#   icons       families carrying Nerd Font glyphs
#
# The icon distinction matters more than it looks. Theme.fontMono is used ONLY
# to draw glyphs -- the workspace pills, the status cluster, the search icon --
# and picking a monospace family without those glyphs replaces every icon in the
# shell with tofu. So they are reported separately rather than lumped in with
# monospace, and the picker can say so.
#
# fc-list reports one line per style, so families are deduplicated here. The
# first comma-separated alias is the canonical name Qt will match.

set -euo pipefail

emit() {
    # $1: fontconfig pattern, $2: json key
    fc-list "$1" family 2>/dev/null \
        | sed 's/,.*//' \
        | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' \
        | grep -v '^$' \
        | sort -u
}

json_array() {
    local first=true
    printf '['
    while IFS= read -r line; do
        [[ -n "$line" ]] || continue
        [[ "$first" == true ]] || printf ','
        first=false
        printf '%s' "$(printf '%s' "$line" | jq -Rs 'rtrimstr("\n")')"
    done
    printf ']'
}

# spacing=100 is fontconfig's mono flag. Proportional is everything else.
mono="$(emit ':spacing=100')"
all="$(emit ':')"
interface="$(comm -23 <(printf '%s\n' "$all") <(printf '%s\n' "$mono"))"
icons="$(printf '%s\n' "$all" | grep -i 'nerd font' || true)"

printf '{"interface":'
printf '%s\n' "$interface" | json_array
printf ',"monospace":'
printf '%s\n' "$mono" | json_array
printf ',"icons":'
printf '%s\n' "$icons" | json_array
printf '}\n'
