"""Build cython extensions and generated files."""

import sys

from Cython.Build import cythonize
from setuptools import setup
from setuptools.command.build_py import build_py
from wcwidth import wcwidth

_CHAR_WIDTHS_DOC = '''\
"""
Character widths as generated by wcwidth.

Each tuple in `CHAR_WIDTHS` represents an interval of ords with common width, i.e.,
`(0, 31, 0)` means ords 0 through 31 (inclusive) have width 0. Intervals with width 1
are omitted so if an ord doesn't belong to any interval we can assume it has width 1.
"""

'''


def _create_char_widths():
    """Build ``_char_widths.py``."""
    groups = []
    start = 0
    group_width = 1
    for codepoint in range(sys.maxunicode + 1):
        char_width = max(wcwidth(chr(codepoint)), 0)
        if char_width != group_width:
            if group_width != 1:
                groups.append((start, codepoint - 1, group_width))
            group_width = char_width
            start = codepoint

    if group_width != 1:
        groups.append((start, codepoint - 1, group_width))

    with open("src/batgrl/_char_widths.py", "w") as file:
        file.write(_CHAR_WIDTHS_DOC)
        file.write("CHAR_WIDTHS = (\n")
        for group in groups:
            file.write(f"    {group},\n")
        file.write(")\n")


class build_py_with_char_widths(build_py):
    """Generate ``_char_widths.py`` on build."""

    def run(self):
        """Generate ``_char_widths.py`` on build."""
        super().run()
        _create_char_widths()


setup(
    ext_modules=cythonize(["src/batgrl/geometry/regions.pyx"]),
    cmdclass={"build_py": build_py_with_char_widths},
)
