// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"regexp"
	"strings"
)

// Older forms stored only the question. Infer familiar field names without an
// LLM call; new forms can set an explicit summary_label for any business field.
var serviceLabelRules = []struct {
	pattern *regexp.Regexp
	label   string
}{
	{regexp.MustCompile(`(?i)\bnama\s+lengkap(?:nya)?\b`), "Nama lengkap"},
	{regexp.MustCompile(`(?i)\bnama\s+(?:produk|barang|kursus|paket)(?:nya)?\b`), "Produk"},
	{regexp.MustCompile(`(?i)\bnama\s+(?:perusahaan|instansi|bisnis|toko)(?:nya)?\b`), "Nama usaha"},
	{regexp.MustCompile(`(?i)\b(?:nama|namanya)\b`), "Nama"},
	{regexp.MustCompile(`(?i)\b(?:e-?mail)(?:nya)?\b`), "Email"},
	{regexp.MustCompile(`(?i)\bnomor\s+(?:pesanan|order|invoice)(?:nya)?\b`), "Nomor pesanan"},
	{regexp.MustCompile(`(?i)\b(?:nomor|no\.?)\s+(?:hp|telepon|wa|whatsapp)(?:nya)?\b`), "Nomor WhatsApp"},
	{regexp.MustCompile(`(?i)\balamat(?:nya)?\b`), "Alamat"},
	{regexp.MustCompile(`(?i)\b(?:kebutuhan|kendala)(?:nya)?\b`), "Kebutuhan"},
	{regexp.MustCompile(`(?i)\b(?:jadwal|waktu|tanggal)(?:nya)?\b`), "Jadwal"},
	{regexp.MustCompile(`(?i)\b(?:berapa\s+orang|jumlah\s+(?:orang|peserta))\b`), "Jumlah peserta"},
	{regexp.MustCompile(`(?i)\b(?:jumlah|kuantitas)(?:nya)?\b`), "Jumlah"},
	{regexp.MustCompile(`(?i)\bcatatan(?:nya)?\b`), "Catatan"},
}

func ServiceFieldSummaryLabel(field ServiceField) string {
	if label := strings.TrimSpace(field.SummaryLabel); label != "" {
		return label
	}
	question := strings.TrimSpace(field.Label)
	// A concise noun label from an older form is already suitable. Preserve it.
	lower := strings.ToLower(question)
	isQuestion := strings.Contains(question, "?")
	for _, prefix := range []string{"boleh ", "silakan ", "tolong ", "apa ", "kapan ", "berapa ", "mohon ", "ketik ", "pilih "} {
		isQuestion = isQuestion || strings.HasPrefix(lower, prefix)
	}
	if !isQuestion && len([]rune(question)) <= 80 && !strings.ContainsAny(question, "\r\n") {
		return strings.TrimRight(question, ":. ")
	}
	for _, rule := range serviceLabelRules {
		if rule.pattern.MatchString(question) {
			return rule.label
		}
	}
	return map[string]string{
		"name": "Nama lengkap", "full_name": "Nama lengkap", "email": "Email",
		"phone": "Nomor WhatsApp", "address": "Alamat", "need": "Kebutuhan",
		"schedule": "Jadwal", "quantity": "Jumlah", "note": "Catatan",
	}[field.Key]
}
