// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"strings"
	"wa-assistant/backend/models"
)

// Relevance only, never a factual verdict. URL identity wins when both sources
// have it. Manual/PDF sources can instead share a distinctive topic anchor; the
// reviewer still checks actual product/scope and whether rules conflict.
func comparisonKnowledgeRelevant(a, b models.Knowledge) bool {
	left, _ := knowledgeSubject(a)
	right, _ := knowledgeSubject(b)
	if left != "" && right != "" {
		return left == right && comparisonScopesCompatible(a.Scope, b.Scope)
	}
	if !comparisonScopesCompatible(a.Scope, b.Scope) {
		return false
	}
	anchors := comparisonAnchors(a.Question)
	if len(anchors) == 0 {
		anchors = comparisonAnchors(a.Answer)
	}
	other := comparisonAnchors(b.Question + " " + b.Answer)
	for anchor := range anchors {
		if other[anchor] {
			return true
		}
	}
	return false
}

func comparisonScopesCompatible(a, b string) bool {
	a, b = strings.ToLower(strings.TrimSpace(a)), strings.ToLower(strings.TrimSpace(b))
	return a == b || a == "" || b == "" || a == "general" || b == "general"
}

func comparisonAnchors(text string) map[string]bool {
	// These are generic question/rule words, not a product or a tenant-specific
	// allowlist. Policy negation is deliberately not used to decide relevance.
	const generic = "apa apakah bagaimana berapa kapan siapa mana boleh tidak belum sudah untuk dengan pada dari yang dan atau ini itu kami saya kamu anda kak kakak ada punya memiliki tersedia termasuk hanya saja setiap semua produk paket kelas kursus layanan aturan syarat ketentuan kebijakan batasan batas lisensi penggunaan izin larangan dijual jual ulang membeli beli harga biaya retur refund garansi sertifikat cara fitur manfaat akses pembayaran informasi tentang terkait berlaku pribadi"
	ignore := map[string]bool{}
	for _, word := range strings.Fields(generic) {
		ignore[word] = true
	}
	out := map[string]bool{}
	for _, token := range knowledgeSubjectTokens(text) {
		if !ignore[token] && !knowledgeAspectFillers[token] {
			out[token] = true
		}
	}
	return out
}
