package replay

import "strings"

// PromptParts captures the two roles the prompt assembly produces.
type PromptParts struct {
	System string
	User   string
}

const systemPrompt = "You are a Lakehouse task executor. Stay grounded — only assert what you can derive from the prior successful patterns or the task itself. " +
	"Do NOT hedge. Do NOT say 'as an AI'. Produce a concrete actionable answer. " +
	"When prior successful outputs are provided, follow their style and format."

// BuildPrompt assembles the system + user messages for a model call.
// When bundle is nil (NoRetrieval mode), the user message is just the
// task — same wording as replay.ts so completions stay comparable.
func BuildPrompt(task string, bundle *ContextBundle) PromptParts {
	if bundle == nil {
		return PromptParts{
			System: systemPrompt,
			User:   "Task: " + task + "\n\nProduce the answer.",
		}
	}

	var b strings.Builder
	if len(bundle.PriorSuccessfulOutputs) > 0 {
		b.WriteString("## Prior successful runs on similar tasks\n\n")
		for _, r := range bundle.PriorSuccessfulOutputs {
			b.WriteString("### ")
			b.WriteString(r.Title)
			b.WriteString(" (score: ")
			b.WriteString(r.SuccessScore)
			b.WriteString(")\n")
			b.WriteString(r.ContentPreview)
			b.WriteString("\n\n")
		}
	}
	if len(bundle.FailurePatterns) > 0 {
		b.WriteString("## Patterns that produced PARTIAL results — avoid these failure modes\n\n")
		for _, r := range bundle.FailurePatterns {
			b.WriteString("- ")
			b.WriteString(r.Title)
			b.WriteString(": ")
			b.WriteString(trim(r.ContentPreview, 160))
			b.WriteByte('\n')
		}
		b.WriteByte('\n')
	}
	if len(bundle.ValidationSteps) > 0 {
		b.WriteString("## Validation checklist (from accepted runs)\n")
		for _, s := range bundle.ValidationSteps {
			b.WriteString("- ")
			b.WriteString(s)
			b.WriteByte('\n')
		}
		b.WriteByte('\n')
	}
	b.WriteString("## Task\n")
	b.WriteString(task)
	b.WriteString("\n\nProduce the answer following the style of the prior successful runs above.")

	return PromptParts{System: systemPrompt, User: b.String()}
}
