"""String snippets."""
import re
import unicodedata

_WORDS = re.compile(r"[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+")


def words(text):
    """Split text into words, understanding camelCase, snake_case and kebab-case.

    >>> words('parseHTTPResponse_code-v2')
    ['parse', 'HTTP', 'Response', 'code', 'v', '2']
    """
    return _WORDS.findall(text)


def snake_case(text):
    """Convert any casing to snake_case.

    >>> snake_case('someHTTPRequest ID')
    'some_http_request_id'
    """
    return '_'.join(w.lower() for w in words(text))


def kebab_case(text):
    """Convert any casing to kebab-case.

    >>> kebab_case('Hello World_again')
    'hello-world-again'
    """
    return '-'.join(w.lower() for w in words(text))


def camel_case(text):
    """Convert any casing to camelCase.

    >>> camel_case('user_id-from header')
    'userIdFromHeader'
    """
    ws = [w.lower() for w in words(text)]
    return ws[0] + ''.join(w.capitalize() for w in ws[1:]) if ws else ''


def pascal_case(text):
    """Convert any casing to PascalCase.

    >>> pascal_case('user_id')
    'UserId'
    """
    return ''.join(w.capitalize() for w in words(text))


def slugify(text):
    """URL-friendly slug: ASCII, lowercase, hyphen separated.

    >>> slugify('  Crème Brûlée: 10 Recipes! ')
    'creme-brulee-10-recipes'
    """
    ascii_text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode()
    return re.sub(r'[^a-z0-9]+', '-', ascii_text.lower()).strip('-')


def truncate(text, length, suffix='...'):
    """Shorten text to at most ``length`` characters including the suffix.

    >>> truncate('The quick brown fox', 10)
    'The qui...'
    >>> truncate('short', 10)
    'short'
    """
    if len(text) <= length:
        return text
    return text[:max(0, length - len(suffix))] + suffix


def is_palindrome(text):
    """Palindrome check that ignores case, spaces and punctuation.

    >>> is_palindrome('A man, a plan, a canal: Panama')
    True
    """
    clean = [c.lower() for c in text if c.isalnum()]
    return clean == clean[::-1]


def is_anagram(a, b):
    """True if two strings use the same letters (case and spaces ignored).

    >>> is_anagram('Dormitory', 'dirty room')
    True
    """
    norm = lambda s: sorted(c.lower() for c in s if c.isalnum())
    return norm(a) == norm(b)


def strip_accents(text):
    """Remove diacritics: é -> e, ñ -> n.

    >>> strip_accents('Café señor')
    'Cafe senor'
    """
    return ''.join(c for c in unicodedata.normalize('NFKD', text) if not unicodedata.combining(c))


def collapse_whitespace(text):
    """Turn every run of whitespace into one space and trim the ends.

    >>> collapse_whitespace('  too   many\\n\\tspaces ')
    'too many spaces'
    """
    return ' '.join(text.split())


def count_vowels(text):
    """Count vowels (a, e, i, o, u), case-insensitive.

    >>> count_vowels('Hello World')
    3
    """
    return sum(c in 'aeiou' for c in text.lower())


def mask(text, visible=4, char='*'):
    """Hide all but the last ``visible`` characters.

    >>> mask('4242424242424242')
    '************4242'
    """
    if visible <= 0:
        return char * len(text)
    return char * max(0, len(text) - visible) + text[-visible:]


def wrap_lines(text, width):
    """Hard-wrap text to ``width`` columns without breaking words.

    >>> wrap_lines('one two three four five', 9)
    ['one two', 'three', 'four five']
    """
    import textwrap
    return textwrap.wrap(text, width)


def remove_prefix_suffix(text, prefix='', suffix=''):
    """Strip one exact prefix and suffix if present (str.removeprefix/removesuffix).

    >>> remove_prefix_suffix('test_utils.py', 'test_', '.py')
    'utils'
    """
    return text.removeprefix(prefix).removesuffix(suffix)


def human_bytes(n, binary=True):
    """Format a byte count for people.

    >>> human_bytes(1536)
    '1.5 KiB'
    >>> human_bytes(1_500_000, binary=False)
    '1.5 MB'
    >>> human_bytes(512)
    '512 B'
    """
    base = 1024 if binary else 1000
    units = ['KiB', 'MiB', 'GiB', 'TiB', 'PiB'] if binary else ['kB', 'MB', 'GB', 'TB', 'PB']
    if abs(n) < base:
        return f'{n} B'
    size = float(n)
    for unit in units:
        size /= base
        if abs(size) < base or unit == units[-1]:
            return f'{size:.1f} {unit}'
