package toc

import (
	"fmt"
	"strings"
)

func (m *Manager) Render() (string, error) {
	categories, err := m.storage.ListCategories()
	if err != nil {
		return "", err
	}

	entriesByCategory, err := m.storage.GetEntriesByCategory()
	if err != nil {
		return "", err
	}

	var sb strings.Builder
	sb.WriteString("📚 **频道目录**\n")
	sb.WriteString("━━━━━━━━━━━━━━━\n\n")

	if len(categories) == 0 {
		sb.WriteString("_暂无分类_")
		return sb.String(), nil
	}

	for _, cat := range categories {
		entries := entriesByCategory[cat.Name]

		sb.WriteString(fmt.Sprintf("📁 **%s**", cat.Name))
		if len(entries) > 0 {
			sb.WriteString(fmt.Sprintf(" (%d)", len(entries)))
		}
		sb.WriteString("\n")

		if len(entries) == 0 {
			sb.WriteString("   _暂无内容_\n")
		} else {
			for _, entry := range entries {
				sb.WriteString(fmt.Sprintf("   • [%s](%s)\n", escapeMarkdown(entry.Title), entry.Link))
			}
		}
		sb.WriteString("\n")
	}

	sb.WriteString("━━━━━━━━━━━━━━━\n")

	return sb.String(), nil
}

func escapeMarkdown(s string) string {
	replacer := strings.NewReplacer(
		"[", "\\[",
		"]", "\\]",
		"(", "\\(",
		")", "\\)",
		"*", "\\*",
		"_", "\\_",
		"`", "\\`",
	)
	return replacer.Replace(s)
}
