"""Swahili number-to-words, for spelling out a piece-unit quantity the
natural Swahili way ("Ndizi kumi na moja") instead of pairing a raw digit
with the "piece" unit's Swahili name — which is itself the number word
"Moja" ("one"), so "11 Moja" reads as nonsense ("11 One"). Every other
registered unit (Kilo, Ndoo, Gunia, Fungu, ...) is a real noun, not a
number, so this conversion is deliberately scoped to piece-quantities
only — see market/measure_units.py and its callers."""

_ONES = {
    1: 'moja', 2: 'mbili', 3: 'tatu', 4: 'nne', 5: 'tano',
    6: 'sita', 7: 'saba', 8: 'nane', 9: 'tisa', 10: 'kumi',
}
_TENS = {
    2: 'ishirini', 3: 'thelathini', 4: 'arobaini', 5: 'hamsini',
    6: 'sitini', 7: 'sabini', 8: 'themanini', 9: 'tisini',
}

_MAX_SUPPORTED = 999_999


def _under_100(n):
    if n <= 10:
        return _ONES[n]
    tens, ones = divmod(n, 10)
    if tens == 1:
        # 11-19: "kumi na X"
        return f'kumi na {_ONES[ones]}' if ones else 'kumi'
    word = _TENS[tens]
    return f'{word} na {_ONES[ones]}' if ones else word


def _under_1000(n):
    if n < 100:
        return _under_100(n)
    hundreds, rest = divmod(n, 100)
    hundreds_word = 'mia moja' if hundreds == 1 else f'mia {_ONES[hundreds]}'
    return f'{hundreds_word} na {_under_100(rest)}' if rest else hundreds_word


def number_to_swahili_words(n):
    """Spells out a positive integer in Swahili, e.g. 25 -> 'ishirini na
    tano', 150 -> 'mia moja na hamsini', 2500 -> 'elfu mbili na mia tano'.
    Falls back to the plain digit string for 0, negatives, or anything
    past a realistic order-quantity ceiling — never raises."""
    if not isinstance(n, int) or n <= 0 or n > _MAX_SUPPORTED:
        return str(n)
    if n < 1000:
        return _under_1000(n)
    thousands, rest = divmod(n, 1000)
    thousands_word = 'elfu moja' if thousands == 1 else f'elfu {_under_1000(thousands)}'
    return f'{thousands_word} na {_under_1000(rest)}' if rest else thousands_word
