// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"math/big"
	"regexp"
	"strconv"
	"strings"
)

var customerNumericSpan = regexp.MustCompile(`(?i)\b(?:rp\.?\s*)?(?:[0-9]+(?:[.,][0-9]+)*(?:\s*(?:ribu|rb|juta|jt))?|(?:` + countWord + `|juta|sejuta)(?:\s+(?:` + countWord + `|juta)){0,9})(?:\s+rupiah)?\b`)

// Normalize numeric notation only. Words about ownership, comparisons, units,
// negation and intent remain intact; equal amounts alone are not a fact review.
func normalizeCustomerNumericSpans(text string) string {
	text = strings.ToLower(strings.Join(strings.Fields(text), " "))
	return customerNumericSpan.ReplaceAllStringFunc(text, func(span string) string {
		if amount, ok := customerNumericAmount(span); ok {
			return "⟦n:" + strconv.FormatInt(amount, 10) + "⟧"
		}
		return span
	})
}

func customerNumericAmount(span string) (int64, bool) {
	value := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(strings.TrimPrefix(span, "rp."), "rp"), "rupiah"))
	if value == "" {
		return 0, false
	}
	if value[0] >= '0' && value[0] <= '9' {
		multiplier := int64(1)
		for _, suffix := range []struct {
			word   string
			factor int64
		}{{"ribu", 1000}, {"rb", 1000}, {"juta", 1000000}, {"jt", 1000000}} {
			if strings.HasSuffix(value, suffix.word) {
				multiplier = suffix.factor
				value = strings.TrimSpace(strings.TrimSuffix(value, suffix.word))
				break
			}
		}
		integerPart := strings.Split(value, ",")[0]
		if rupiahGroupingPattern.MatchString(integerPart) {
			value = strings.ReplaceAll(value, ".", "")
		} else if strings.Contains(value, ".") && multiplier == 1 {
			return 0, false
		}
		// Indonesian decimal comma; reject ambiguous/multiple separators.
		value = strings.ReplaceAll(value, ",", ".")
		rational, ok := new(big.Rat).SetString(value)
		if !ok {
			return 0, false
		}
		rational.Mul(rational, new(big.Rat).SetInt64(multiplier))
		if !rational.IsInt() || !rational.Num().IsInt64() {
			return 0, false
		}
		n := rational.Num().Int64()
		return n, n > 0 && n <= 1_000_000_000_000
	}
	if strings.HasPrefix(value, "sejuta") {
		value = strings.Replace(value, "sejuta", "satu juta", 1)
	}
	if parts := strings.Split(value, " juta"); len(parts) == 2 {
		millions, ok := ParseCustomerCount(strings.TrimSpace(parts[0]))
		rest, valid := 0, true
		if strings.TrimSpace(parts[1]) != "" {
			rest, valid = ParseCustomerCount(strings.TrimSpace(parts[1]))
		}
		return int64(millions)*1_000_000 + int64(rest), ok && valid && millions <= 999999
	}
	n, ok := ParseCustomerCount(value)
	return int64(n), ok
}
