package proxy

import (
	"regexp"

	"github.com/veylant/ia-gateway/internal/pii"
)

// piiTokenRegex matches pseudonymization tokens of the form [PII:TYPE:8hexchars].
var piiTokenRegex = regexp.MustCompile(`\[PII:[A-Z_]+:[0-9a-f]{8}\]`)

// BuildEntityMap transforms the entity list returned by the PII service into a
// map from pseudonym token → original value, used for de-pseudonymization.
func BuildEntityMap(entities []pii.Entity) map[string]string {
	m := make(map[string]string, len(entities))
	for _, e := range entities {
		if e.Pseudonym != "" {
			m[e.Pseudonym] = e.OriginalValue
		}
	}
	return m
}

// Depseudonymize replaces all [PII:TYPE:UUID] tokens in text with their
// original values from entityMap. Tokens not found in the map are left as-is.
func Depseudonymize(text string, entityMap map[string]string) string {
	if len(entityMap) == 0 {
		return text
	}
	return piiTokenRegex.ReplaceAllStringFunc(text, func(token string) string {
		if original, ok := entityMap[token]; ok {
			return original
		}
		return token
	})
}
