// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"regexp"
	"strings"
)

// Participant counts are purchase quantities for services. Ages, dates, trip
// duration and room capacity are not. Keep this independent of a business name.
var serviceQuantityPattern = regexp.MustCompile(`(?i)\b(` + countQuote + `)\s*(orang|peserta|jamaah|jemaah|pax|tamu|penumpang|anggota|dewasa|anak|bayi)\b(?:\s+(dewasa|anak|bayi))?`)
var serviceCapacitySuffix = regexp.MustCompile(`(?i)^\s*(?:/\s*kamar|per\s+kamar|sekamar)\b`)
var serviceCapacityPrefix = regexp.MustCompile(`(?i)\b(?:kapasitas|berkapasitas|muat|kamar\s+(?:quad|triple|double))\s*:?\s*$`)
var serviceCollectivePattern = regexp.MustCompile(`(?i)\b(?:kami|kita|untuk)\s+(berdua|bertiga|berempat|berlima|berenam|bertujuh|berdelapan|bersembilan|bersepuluh)\b`)
var serviceCountCorrection = regexp.MustCompile(`(?i)\b(?:jadi|ganti|eh|koreksi|bukan)\b`)
var servicePersonCategory = regexp.MustCompile(`(?i)\b(dewasa|anak|bayi)\b`)

func customerServiceQuantity(text, priceEvidence string) (int64, bool) {
	type count struct {
		value    int64
		category string
	}
	var counts []count
	for _, match := range serviceQuantityPattern.FindAllStringSubmatchIndex(text, -1) {
		if serviceCapacitySuffix.MatchString(text[match[1]:]) || serviceCapacityPrefix.MatchString(text[:match[0]]) {
			continue
		}
		n, ok := ParseCustomerCount(text[match[2]:match[3]])
		if !ok {
			continue
		}
		unit := strings.ToLower(text[match[4]:match[5]])
		category := ""
		if unit == "dewasa" || unit == "anak" || unit == "bayi" {
			category = unit
		}
		if match[6] >= 0 {
			category = strings.ToLower(text[match[6]:match[7]])
		}
		counts = append(counts, count{int64(n), category})
	}
	if len(counts) == 0 {
		if match := serviceCollectivePattern.FindStringSubmatch(text); len(match) > 0 {
			n, ok := ParseCustomerCount(match[1])
			return int64(n), ok
		}
		return 0, false
	}
	scopes := map[string]bool{}
	for _, category := range servicePersonCategory.FindAllString(strings.ToLower(priceEvidence), -1) {
		scopes[category] = true
	}
	scope := ""
	if len(scopes) == 1 {
		for category := range scopes {
			scope = category
		}
	}
	var candidates []int64
	for _, c := range counts {
		if scope != "" && c.category == scope {
			candidates = append(candidates, c.value)
		}
	}
	if len(candidates) == 0 {
		for _, c := range counts {
			// Mixed ages cannot silently share an unqualified price, and a price
			// for adults cannot be multiplied by an explicitly child-only count.
			if c.category != "" && (scope != c.category || len(counts) > 1) {
				return 0, true
			}
			candidates = append(candidates, c.value)
		}
	}
	for _, n := range candidates {
		if n != candidates[len(candidates)-1] && !serviceCountCorrection.MatchString(text) {
			return 0, true
		}
	}
	return candidates[len(candidates)-1], true
}
