"""Chinese uses KaiTi; Latin, numeric and unit glyphs use Times New Roman."""

FONT_FAMILY = "\u6977\u4f53"
FONT_ALIASES = (FONT_FAMILY, "KaiTi")
LATIN_FONT = "Times New Roman"
FONT_CSS = '"Times New Roman", "KaiTi", "\u6977\u4f53", serif'
FONT_SVG = "Times New Roman, KaiTi, \u6977\u4f53, serif"


def font_runs(text):
    """Preserve text exactly while grouping Chinese and Western glyphs."""
    runs = []
    for char in str(text):
        code = ord(char)
        chinese = (0x2E80 <= code <= 0x9FFF or 0xF900 <= code <= 0xFAFF
                   or 0xFE30 <= code <= 0xFE4F or 0x20000 <= code <= 0x323AF
                   or char in "\uff0c\uff0e\uff1a\uff1b\uff01\uff1f\uff08\uff09\uff3b\uff3d\uff5b\uff5d")
        family = FONT_FAMILY if chinese else LATIN_FONT
        if runs and runs[-1][0] == family:
            runs[-1] = (family, runs[-1][1] + char)
        else:
            runs.append((family, char))
    return runs


def configure_tk_fonts(root):
    """Configure application-owned widgets without changing OS font settings."""
    from tkinter import font, ttk

    installed = set(font.families(root))
    selected = next((name for name in FONT_ALIASES if name in installed), FONT_FAMILY)
    for name in font.names(root):
        family = LATIN_FONT if name == "TkFixedFont" else selected
        font.nametofont(name, root=root).configure(family=family)
    root.option_add("*Font", (selected, 11))
    ttk.Style(root).configure(".", font=(selected, 11))
    return selected in installed and LATIN_FONT in installed


def mixed_tk_label(parent, variable, *, size=10, background="white", foreground="black", height=2):
    """Read-only native status text with per-script font tags."""
    import tkinter as tk

    widget = tk.Text(parent, height=height, width=1, wrap="word", borderwidth=0,
                     highlightthickness=0, background=background, foreground=foreground,
                     cursor="arrow", takefocus=False, font=(FONT_FAMILY, size))
    widget.tag_configure("chinese", font=(FONT_FAMILY, size))
    widget.tag_configure("western", font=(LATIN_FONT, size))

    def refresh(*_args):
        widget.configure(state="normal")
        widget.delete("1.0", "end")
        for family, value in font_runs(variable.get()):
            widget.insert("end", value, "chinese" if family == FONT_FAMILY else "western")
        widget.configure(state="disabled")

    trace = variable.trace_add("write", refresh)
    widget.bind("<Destroy>", lambda event: variable.trace_remove("write", trace)
                if event.widget == widget else None, add=True)
    refresh()
    return widget
