package com.applemand.zmanim.core.jewcal

/**
 * Gematria for positive integers 1..999, following standard printed conventions.
 * Ported from `getDafYomi/entry.ts` toHebrewNumerals + tikanim for 15/16 (ט״ו / ט״ז)
 * and gershayim/geresh placement.
 */
object HebrewNumerals {
    private val ones = arrayOf("", "א", "ב", "ג", "ד", "ה", "ו", "ז", "ח", "ט")
    private val tens = arrayOf("", "י", "כ", "ל", "מ", "נ", "ס", "ע", "פ", "צ")
    private val hundreds = arrayOf("", "ק", "ר", "ש", "ת")

    fun format(n: Int): String {
        require(n in 1..999) { "out of range: $n" }
        val sb = StringBuilder()
        var remaining = n

        // Hundreds: 100..400 are direct letters (ק ר ש ת); 500..900 stack ת's
        // and add the remainder. E.g. 900 = תתק (400+400+100), 999 = תתקצ״ט.
        var h = remaining / 100
        remaining %= 100
        while (h >= 4) {
            sb.append(hundreds[4])
            h -= 4
        }
        if (h > 0) sb.append(hundreds[h])

        // Tens + ones with 15 → ט״ו and 16 → ט״ז.
        when (remaining) {
            15 -> sb.append("טו")
            16 -> sb.append("טז")
            else -> {
                val t = remaining / 10
                val o = remaining % 10
                if (t > 0) sb.append(tens[t])
                if (o > 0) sb.append(ones[o])
            }
        }

        // Punctuation: gershayim (״) before the last letter for multi-letter,
        // geresh (׳) after a single letter.
        return when (sb.length) {
            0 -> ""
            1 -> sb.append('\u05F3').toString()
            else -> {
                sb.insert(sb.length - 1, '\u05F4')
                sb.toString()
            }
        }
    }
}
