# -*- coding: utf-8 -*-
"""Add-on versions compared exactly as Kodi 21 compares them (CAddonVersion, xbmc/addons/AddonVersion.cpp, Omega).

`[epoch:]upstream[-revision]`, Debian style: numbers compare as numbers, `~` sorts before everything, even the end, so
the beta `2.3.6~beta20261116190000` comes before the release `2.3.6` (docs/plan/skin-milionar/340-beta-channel.md).
Only the standard library: scripts/release.py loads this file too.
"""
VALID = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.+_@~')
DIGITS = '0123456789'


def _parse(version):
    upstream, epoch, revision = (version or '0.0.0').lower(), 0, ''
    if ':' in upstream:
        head, upstream = upstream.split(':', 1)
        digits = ''
        for char in head.lstrip():
            if char not in DIGITS:
                break
            digits += char
        epoch = int(digits or 0)
    if '-' in upstream:
        upstream, revision = upstream.split('-', 1)
        if not set(revision) <= VALID:
            revision = ''
    if not set(upstream) <= VALID:
        upstream = '0.0.0'
    return epoch, upstream, revision


def _number(text, index):
    end = index
    while end < len(text) and text[end] in DIGITS:
        end += 1
    return int(text[index:end] or 0), end


def _component(a, b):
    """CAddonVersion::CompareComponent: -1, 0 or 1."""
    i = j = 0
    while i < len(a) and j < len(b):
        while i < len(a) and j < len(b) and a[i] not in DIGITS and b[j] not in DIGITS:
            if a[i] != b[j]:
                if a[i] == '~':
                    return -1
                if b[j] == '~':
                    return 1
                return -1 if a[i] < b[j] else 1
            i, j = i + 1, j + 1
        if i < len(a) and j < len(b) and (a[i] not in DIGITS or b[j] not in DIGITS):
            if a[i] == '~':
                return -1
            if b[j] == '~':
                return 1
            return -1 if a[i] in DIGITS else 1
        number_a, i = _number(a, i)
        number_b, j = _number(b, j)
        if number_a != number_b:
            return -1 if number_a < number_b else 1
    if i == len(a) and j == len(b):
        return 0
    if i < len(a):
        return -1 if a[i] == '~' else 1
    return 1 if b[j] == '~' else -1


def compare(a, b):
    """-1, 0 or 1 as version a is older than, the same as or newer than b."""
    (epoch_a, upstream_a, revision_a), (epoch_b, upstream_b, revision_b) = _parse(a), _parse(b)
    if epoch_a != epoch_b:
        return -1 if epoch_a < epoch_b else 1
    return _component(upstream_a, upstream_b) or _component(revision_a, revision_b)


def newer(a, b):
    return compare(a, b) > 0


def is_prerelease(version):
    """A beta (or any `~` prerelease): it sorts before the release it leads to."""
    return '~' in (version or '')
