package webpage

import (
	"strings"
)

// FormatMarkdownBlock renders digests for LLM prompts.
func FormatMarkdownBlock(digests []Digest, maxTotal int) string {
	if len(digests) == 0 {
		return ""
	}
	if maxTotal <= 0 {
		maxTotal = DefaultMaxMarkdown
	}
	var b strings.Builder
	used := 0
	for i, item := range digests {
		if used >= maxTotal {
			break
		}
		section := formatDigestSection(item)
		if section == "" {
			continue
		}
		if i > 0 {
			b.WriteString("\n\n---\n\n")
		}
		remain := maxTotal - used
		runes := []rune(section)
		if len(runes) > remain {
			section = string(runes[:remain]) + "…"
		}
		b.WriteString(section)
		used += len([]rune(section))
	}
	return strings.TrimSpace(b.String())
}

func formatDigestSection(item Digest) string {
	if strings.TrimSpace(item.Markdown) != "" {
		var b strings.Builder
		b.WriteString("來源：")
		b.WriteString(item.URL)
		b.WriteString("\n")
		b.WriteString(item.Markdown)
		return strings.TrimSpace(b.String())
	}
	if strings.TrimSpace(item.Error) == "" {
		return ""
	}
	return "來源：" + item.URL + "\n（抓取失敗：" + item.Error + "）"
}
