#!/usr/bin/env python
# License: GPLv3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>

from collections import defaultdict

from calibre.utils.icu import ord_string


def character_name_from_code(code):
    from calibre_extensions.unicode_names import name_for_codepoint

    return name_for_codepoint(code) or f'U+{code:X}'


_html_entities_cache: dict | None = None


def html_entities():
    global _html_entities_cache
    if _html_entities_cache is None:
        from calibre.ebooks.html_entities import html5_entities

        ans = defaultdict(set)
        for name, char in html5_entities.items():
            try:
                ans[name.lower()].add(ord_string(char)[0])
            except TypeError:
                continue
        ans['nnbsp'].add(0x202F)
        _html_entities_cache = dict(ans)
    return _html_entities_cache


_points_for_word_cache: dict = {}


def points_for_word(w):
    """Returns the set of all codepoints that contain ``word`` in their names"""
    w = w.lower()
    ans = _points_for_word_cache.get(w)
    if ans is None:
        from calibre_extensions.unicode_names import codepoints_for_word

        ans = codepoints_for_word(w) | html_entities().get(w, set())
        _points_for_word_cache[w] = ans
    return ans
