package app import ( "encoding/json" "fmt" "regexp" "strings" "github.com/geo-platform/tenant-api/internal/shared/contentstats" "github.com/geo-platform/tenant-api/internal/tenant/prompts" ) var promptVariablePattern = regexp.MustCompile(`\{\{\s*([a-zA-Z0-9_]+)\s*\}\}`) func buildGenerationPrompt( templateKey, templateName string, promptTemplate *string, params map[string]interface{}, knowledgePrompt string, ) string { basePrompt := strings.TrimSpace(renderPromptTemplate(promptTemplate, params)) if basePrompt == "" { basePrompt = prompts.DefaultGenerationBasePrompt(templateName) } var sections []string sections = append(sections, basePrompt) contextBlock := buildPromptContext(params) if contextBlock != "" { sections = append(sections, prompts.PromptContextSection(contextBlock)) } if strings.TrimSpace(knowledgePrompt) != "" { sections = append(sections, knowledgePrompt) } sections = append(sections, prompts.GenerationWritingRequirementsSection()) if templateRules := buildTemplateSpecificWritingRules(templateKey, params); templateRules != "" { sections = append(sections, prompts.GenerationTemplateSpecificRulesHeading()+"\n"+templateRules) } if lengthGuidance := buildGenerationLengthGuidance(params); lengthGuidance != "" { sections = append(sections, prompts.GenerationLengthGuidanceHeading()+"\n"+lengthGuidance) } return strings.Join(sections, "\n\n") } func buildGenerationKnowledgeQuery(params map[string]interface{}) string { if len(params) == 0 { return "" } parts := make([]string, 0, 8) appendValue := func(value string) { value = strings.TrimSpace(value) if value == "" { return } parts = append(parts, value) } appendValue(stringValue(params["title"])) appendValue(stringValue(params["topic"])) appendValue(stringValue(params["product_name"])) appendValue(stringValue(params["subject"])) appendValue(stringValue(params["brand_name"])) appendValue(stringValue(params["primary_keyword"])) appendValue(stringValue(params["key_points"])) appendValue(stringValue(params["review_intro_hook"])) return strings.Join(parts, "\n") } func buildTemplateSpecificWritingRules(templateKey string, params map[string]interface{}) string { switch strings.TrimSpace(templateKey) { case "top_x_article": brandName := strings.TrimSpace(stringValue(params["brand_name"])) if brandName == "" { return "" } return prompts.TopXBrandPriorityRules(brandName) default: return "" } } func buildGenerationLengthGuidance(params map[string]interface{}) string { sectionCount := estimateTopLevelSectionCount(params) if sectionCount <= 0 { sectionCount = 4 } locale := strings.TrimSpace(stringValue(params["locale"])) if locale == "en-US" { minWords := 900 targetWords := 320 + sectionCount*130 if targetWords > minWords { minWords = targetWords } if minWords > 1600 { minWords = 1600 } maxWords := minWords + 400 if maxWords > 2100 { maxWords = 2100 } return prompts.EnglishLengthGuidance(minWords, maxWords) } minChars := 1100 targetChars := 320 + sectionCount*180 if targetChars > minChars { minChars = targetChars } if minChars > 1800 { minChars = 1800 } maxChars := minChars + 500 if maxChars > 2400 { maxChars = 2400 } return prompts.ChineseLengthGuidance(minChars, maxChars) } func estimateTopLevelSectionCount(params map[string]interface{}) int { if params == nil { return 0 } switch value := params["article_outline"].(type) { case []interface{}: if len(value) > 0 { return len(value) } case []map[string]interface{}: if len(value) > 0 { return len(value) } } switch value := params["outline_sections"].(type) { case []interface{}: if len(value) > 0 { return len(value) } case []string: if len(value) > 0 { return len(value) } } return 0 } func renderPromptTemplate(promptTemplate *string, params map[string]interface{}) string { if promptTemplate == nil { return "" } return promptVariablePattern.ReplaceAllStringFunc(*promptTemplate, func(match string) string { submatches := promptVariablePattern.FindStringSubmatch(match) if len(submatches) != 2 { return match } value, ok := params[submatches[1]] if !ok { return "" } return formatPromptValue(value) }) } func buildPromptContext(params map[string]interface{}) string { if len(params) == 0 { return "" } orderedKeys := []string{ "locale", "title", "topic", "product_name", "subject", "brand_name", "primary_keyword", "brand", "category", "count", "depth", "article_outline", "outline_sections", "key_points", "review_intro_hook", "keywords", "competitors", } used := make(map[string]struct{}, len(params)) lines := make([]string, 0, len(params)) appendLine := func(key string, value interface{}) { if value == nil { return } switch key { case "knowledge_group_ids", "knowledge_groups", "knowledge_context": return } if key == "outline_sections" && hasStructuredOutline(params["article_outline"]) { return } formatted := strings.TrimSpace(formatPromptContextValue(key, value)) if formatted == "" { return } lines = append(lines, fmt.Sprintf("- %s: %s", promptContextLabel(key), formatted)) used[key] = struct{}{} } for _, key := range orderedKeys { appendLine(key, params[key]) } for key, value := range params { if _, ok := used[key]; ok { continue } appendLine(key, value) } return strings.Join(lines, "\n") } func promptContextLabel(key string) string { return prompts.ContextLabel(key) } func formatPromptContextValue(key string, value interface{}) string { switch key { case "keywords": return formatKeywordList(value, 6) case "competitors": return formatCompetitorList(value, 6) case "outline_sections": return formatSectionList(value, 10) case "article_outline": return formatOutlineValue(value) default: return formatPromptValue(value) } } func formatPromptValue(value interface{}) string { switch v := value.(type) { case nil: return "" case string: return strings.TrimSpace(v) case []string: return strings.Join(v, ", ") case []interface{}: if hasOutlineItems(v) { return formatOutlineItems(v, 0) } if hasNamedItems(v) { return formatNamedItems(v, 6) } parts := make([]string, 0, len(v)) for _, item := range v { formatted := strings.TrimSpace(formatPromptValue(item)) if formatted != "" { parts = append(parts, formatted) } } return strings.Join(parts, ", ") default: bytes, err := json.Marshal(v) if err != nil { return fmt.Sprint(v) } return string(bytes) } } func formatKeywordList(value interface{}, limit int) string { items := extractStringList(value, limit) return strings.Join(items, ", ") } func formatSectionList(value interface{}, limit int) string { items := extractStringList(value, limit) return strings.Join(items, " > ") } func formatCompetitorList(value interface{}, limit int) string { switch items := value.(type) { case []interface{}: names := make([]string, 0, len(items)) for _, item := range items { if data, ok := item.(map[string]interface{}); ok { name := strings.TrimSpace(stringValue(data["name"])) if name == "" { name = strings.TrimSpace(stringValue(data["brand_name"])) } if name != "" { names = append(names, name) } } if len(names) >= limit { break } } return strings.Join(names, ", ") default: return formatPromptValue(value) } } func formatOutlineValue(value interface{}) string { switch items := value.(type) { case []interface{}: return formatOutlineItems(items, 0) default: return formatPromptValue(value) } } func hasStructuredOutline(value interface{}) bool { switch items := value.(type) { case []interface{}: return hasOutlineItems(items) default: return false } } func hasOutlineItems(items []interface{}) bool { for _, item := range items { if data, ok := item.(map[string]interface{}); ok { if strings.TrimSpace(stringValue(data["outline"])) != "" { return true } } } return false } func hasNamedItems(items []interface{}) bool { for _, item := range items { if data, ok := item.(map[string]interface{}); ok { if strings.TrimSpace(stringValue(data["name"])) != "" || strings.TrimSpace(stringValue(data["brand_name"])) != "" { return true } } } return false } func formatNamedItems(items []interface{}, limit int) string { names := make([]string, 0, len(items)) for _, item := range items { data, ok := item.(map[string]interface{}) if !ok { continue } name := strings.TrimSpace(stringValue(data["name"])) if name == "" { name = strings.TrimSpace(stringValue(data["brand_name"])) } if name == "" { continue } names = append(names, name) if len(names) >= limit { break } } return strings.Join(names, ", ") } func formatOutlineItems(items []interface{}, level int) string { lines := make([]string, 0) indent := strings.Repeat(" ", level) for _, item := range items { node, ok := item.(map[string]interface{}) if !ok { continue } outline := strings.TrimSpace(stringValue(node["outline"])) if outline == "" { continue } lines = append(lines, fmt.Sprintf("%s- %s", indent, outline)) children, ok := node["children"].([]interface{}) if ok && len(children) > 0 { childText := formatOutlineItems(children, level+1) if childText != "" { lines = append(lines, childText) } } } return strings.Join(lines, "\n") } func extractStringList(value interface{}, limit int) []string { items := make([]string, 0) appendItem := func(text string) { text = strings.TrimSpace(text) if text == "" { return } items = append(items, text) } switch list := value.(type) { case []string: for _, item := range list { appendItem(item) if limit > 0 && len(items) >= limit { break } } case []interface{}: for _, item := range list { appendItem(formatPromptValue(item)) if limit > 0 && len(items) >= limit { break } } } return items } func resolveArticleTitle(params map[string]interface{}, markdown string) string { if title := strings.TrimSpace(stringValue(params["title"])); title != "" { return title } if topic := strings.TrimSpace(stringValue(params["topic"])); topic != "" { return topic } if product := strings.TrimSpace(stringValue(params["product_name"])); product != "" { return product + " Review" } if subject := strings.TrimSpace(stringValue(params["subject"])); subject != "" { return subject + " Report" } for _, line := range strings.Split(markdown, "\n") { line = strings.TrimSpace(line) if strings.HasPrefix(line, "#") { return strings.TrimSpace(strings.TrimLeft(line, "#")) } } return "Generated Article" } func estimateWordCount(markdown string) int { return contentstats.CountWords(markdown) } func stringValue(value interface{}) string { if value == nil { return "" } text, ok := value.(string) if !ok { return "" } return text }