package adapter

import (
	"regexp"
	"strings"
)

// placeholder matches {{NAME}} in the prompt template.
var placeholder = regexp.MustCompile(`\{\{(\w+)\}\}`)

// renderPrompt fills the template from one dispatch.
//
// A name the template uses and this does not know is left standing rather than
// replaced with an empty string: a prompt that quietly loses a section reads as
// a working prompt, and the misspelling would only surface as an agent that
// mysteriously ignores half its instructions.
func renderPrompt(template string, d *Dispatch, proxyURL string) string {
	runbook := d.RunbookURL
	if runbook == "" {
		runbook = "(no runbook_url)"
	}

	fields := map[string]string{
		"ALERT_ID":       d.AlertID,
		"ALERTNAME":      d.Alertname,
		"CLASSIFICATION": d.Classification,
		"CLUSTER_ID":     d.ClusterID,
		"TENANT_ID":      d.TenantID,
		"DESCRIPTION":    d.Description,
		"RUNBOOK_URL":    runbook,
		"CALLBACK_URL":   d.Callback.URL,
		"PROXY_URL":      strings.TrimRight(proxyURL, "/"),
	}

	return placeholder.ReplaceAllStringFunc(template, func(whole string) string {
		name := placeholder.FindStringSubmatch(whole)[1]
		if value, ok := fields[name]; ok {
			return value
		}
		return whole
	})
}
