package i18n

import "strings"

// Transliterate writes English phonetically in Sumero-Akkadian
// cuneiform (Unicode U+12000). Digits and punctuation stay, so a
// sentence keeps its shape. Printf verbs (%s, %d, %q, %%) stay
// literal, so a dialog can still substitute a name. The spelling
// is syllabic: consonants without a following vowel take an
// inherent a, o is written u, and there is no separate sign for
// f, v or o. igh and eigh are the same diphthong as ai.
func Transliterate(s string) string {
	var b strings.Builder
	word := strings.Builder{}
	flush := func() {
		if word.Len() == 0 {
			return
		}
		b.WriteString(encodeWord(word.String()))
		word.Reset()
	}
	rs := []rune(s)
	for i := 0; i < len(rs); i++ {
		if n := printfVerb(rs[i:]); n > 0 {
			flush()
			b.WriteString(string(rs[i : i+n]))
			i += n - 1
			continue
		}
		r := rs[i]
		if isLetter(r) || r == '\'' {
			word.WriteRune(r)
			continue
		}
		flush()
		b.WriteRune(r)
	}
	flush()
	return b.String()
}

// printfVerb is the length of a Go fmt verb at the start of rs,
// including %%. Zero means rs does not begin with a verb.
func printfVerb(rs []rune) int {
	if len(rs) < 2 || rs[0] != '%' {
		return 0
	}
	if rs[1] == '%' {
		return 2
	}
	i := 1
	for i < len(rs) && strings.ContainsRune("#0-+ ", rs[i]) {
		i++
	}
	if i < len(rs) && rs[i] == '[' {
		j := i + 1
		for j < len(rs) && rs[j] >= '0' && rs[j] <= '9' {
			j++
		}
		if j > i+1 && j < len(rs) && rs[j] == ']' {
			i = j + 1
		}
	}
	for i < len(rs) && rs[i] >= '0' && rs[i] <= '9' {
		i++
	}
	if i < len(rs) && rs[i] == '.' {
		k := i + 1
		for k < len(rs) && rs[k] >= '0' && rs[k] <= '9' {
			k++
		}
		if k > i+1 {
			i = k
		}
	}
	if i < len(rs) && isPrintfVerb(rs[i]) {
		return i + 1
	}
	return 0
}

func isPrintfVerb(r rune) bool {
	switch r {
	case 'b', 'c', 'd', 'e', 'E', 'f', 'g', 'G', 'o', 'p', 'q', 's', 't', 'T', 'U', 'v', 'w', 'x', 'X':
		return true
	default:
		return false
	}
}

func isLetter(r rune) bool {
	return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')
}

func encodeWord(raw string) string {
	ph := phonemes(raw)
	if len(ph) == 0 {
		return ""
	}
	var out []rune
	i := 0
	for i < len(ph) {
		if i+2 < len(ph) && isC(ph[i]) && isV(ph[i+1]) && isC(ph[i+2]) && (i+3 == len(ph) || isC(ph[i+3])) {
			if sign, ok := signs[ph[i]+ph[i+1]+ph[i+2]]; ok {
				out = append(out, sign)
				i += 3
				continue
			}
		}
		if i+1 < len(ph) && isC(ph[i]) && isV(ph[i+1]) {
			if sign, ok := cv(ph[i], ph[i+1]); ok {
				out = append(out, sign)
				i += 2
				continue
			}
		}
		if i+1 < len(ph) && isV(ph[i]) && isC(ph[i+1]) && (i+2 == len(ph) || isC(ph[i+2])) {
			if sign, ok := signs[ph[i]+ph[i+1]]; ok {
				out = append(out, sign)
				i += 2
				continue
			}
		}
		if isV(ph[i]) {
			if sign, ok := signs[ph[i]]; ok {
				out = append(out, sign)
			}
			i++
			continue
		}
		if sign, ok := cv(ph[i], "a"); ok {
			out = append(out, sign)
		}
		i++
	}
	return string(out)
}

func cv(c, v string) (rune, bool) {
	if v == "e" {
		if sign, ok := signs[c+"e"]; ok {
			return sign, true
		}
		if sign, ok := signs[c+"i"]; ok {
			return sign, true
		}
	}
	sign, ok := signs[c+v]
	return sign, ok
}

func isC(s string) bool { return s != "a" && s != "e" && s != "i" && s != "u" }
func isV(s string) bool { return !isC(s) }

func phonemes(raw string) []string {
	s := strings.ToLower(raw)
	var out []string
	for i := 0; i < len(s); i++ {
		if i+3 < len(s) && s[i:i+4] == "eigh" {
			out = append(out, "e")
			i += 3
			continue
		}
		if i+2 < len(s) && s[i:i+3] == "igh" {
			out = append(out, "e")
			i += 2
			continue
		}
		if i+1 < len(s) {
			switch s[i : i+2] {
			case "qu":
				out = append(out, "k", "w")
				i++
				continue
			case "ck":
				out = append(out, "k")
				i++
				continue
			case "ph":
				out = append(out, "p")
				i++
				continue
			case "th":
				out = append(out, "t")
				i++
				continue
			case "sh":
				out = append(out, "š")
				i++
				continue
			case "ch":
				out = append(out, "š")
				i++
				continue
			case "wh":
				out = append(out, "w")
				i++
				continue
			case "ng":
				out = append(out, "n")
				i++
				continue
			case "ee", "ea":
				out = append(out, "i")
				i++
				continue
			case "oo", "ou":
				out = append(out, "u")
				i++
				continue
			case "ai", "ay":
				out = append(out, "e")
				i++
				continue
			}
		}
		c := s[i]
		switch c {
		case 'a', 'e', 'i', 'u':
			out = append(out, string(c))
		case 'o':
			out = append(out, "u")
		case 'y':
			if i == 0 || isVowelByte(s[i-1]) {
				out = append(out, "y")
			} else {
				out = append(out, "i")
			}
		case 'c':
			if i+1 < len(s) && (s[i+1] == 'e' || s[i+1] == 'i' || s[i+1] == 'y') {
				out = append(out, "s")
			} else {
				out = append(out, "k")
			}
		case 'f':
			out = append(out, "p")
		case 'v':
			out = append(out, "b")
		case 'j':
			out = append(out, "y")
		case 'q':
			out = append(out, "k")
		case 'x':
			out = append(out, "k", "s")
		case 'b', 'd', 'g', 'h', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'w', 'z':
			out = append(out, string(c))
		}
	}
	compact := out[:0]
	for _, p := range out {
		if len(compact) > 0 && compact[len(compact)-1] == p && isC(p) {
			continue
		}
		compact = append(compact, p)
	}
	return compact
}

func isVowelByte(c byte) bool {
	return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y'
}

// signs maps a conventional Akkadian reading to one sign.
// pu is written with BU, and w+vowel with PI, which are the usual values.
var signs = map[string]rune{
	"a": '𒀀', "e": '𒂊', "i": '𒄿', "u": '𒌋',
	"ba": '𒁀', "bi": '𒁉', "bu": '𒁍', "pu": '𒁍',
	"da": '𒁕', "di": '𒁲', "du": '𒁺',
	"ga": '𒂵', "gi": '𒄀', "gu": '𒄖',
	"ha": '𒄩', "hi": '𒄭', "hu": '𒄷',
	"ka": '𒅗', "ki": '𒆠', "ku": '𒆪',
	"la": '𒆷', "li": '𒇷', "lu": '𒇻',
	"ma": '𒈠', "me": '𒈨', "mi": '𒈪', "mu": '𒈬',
	"na": '𒈾', "ne": '𒉈', "ni": '𒉌', "nu": '𒉡',
	"pa": '𒉺', "pi": '𒉿',
	"ra": '𒊏', "ri": '𒊑', "ru": '𒊒',
	"sa": '𒊓', "si": '𒋛', "su": '𒋢',
	"ša": '𒊭', "še": '𒊺', "ši": '𒅆', "šu": '𒋗',
	"ta": '𒋫', "te": '𒋼', "ti": '𒋾', "tu": '𒌅',
	"wa": '𒉿', "we": '𒉿', "wi": '𒉿', "wu": '𒉿',
	"ya": '𒅀', "za": '𒍝', "zi": '𒍣', "zu": '𒍪',
	"ab": '𒀊', "ad": '𒀜', "ak": '𒀝', "al": '𒀠', "an": '𒀭', "aš": '𒀸',
	"el": '𒂖', "en": '𒂗', "eš": '𒂠',
	"ib": '𒅁', "ig": '𒅅', "il": '𒅋', "im": '𒅎', "in": '𒅔', "ir": '𒅕', "iš": '𒅖',
	"ub": '𒌒', "ud": '𒌓', "um": '𒌝', "un": '𒌦', "ur": '𒌨', "uš": '𒍑',
	"bad": '𒁁', "bal": '𒁄', "bar": '𒁇',
	"dag": '𒁖', "dam": '𒁮', "dar": '𒁯',
	"dib": '𒁳', "dim": '𒁴', "din": '𒁷',
	"dub": '𒁾', "dug": '𒂁', "dun": '𒂄',
	"gal": '𒃲', "gam": '𒃵', "gan": '𒃶', "gar": '𒃻',
	"gul": '𒄢', "gur": '𒄥',
	"hal": '𒄬',
	"kal": '𒆗', "kin": '𒆥', "kul": '𒆰', "kur": '𒆳',
	"lal": '𒇲', "lam": '𒇴', "lum": '𒈝',
	"mar": '𒈥',
	"nam": '𒉆', "nun": '𒉣',
	"pad": '𒉻', "pap": '𒉽',
	"rab": '𒊐',
	"sag": '𒊕', "sar": '𒊬',
	"tab": '𒋰', "tag": '𒋳', "tar": '𒋻',
	"tum": '𒌈', "tur": '𒌉',
	"zag": '𒍠',
}
