package cms

import (
	"regexp"
	"strings"
)

var (
	standaloneMarkdownLink = regexp.MustCompile(`^\s*\[([^\]]+)\]\(([^)]+)\)\s*$`)
	inlineMarkdownLink     = regexp.MustCompile(`\[([^\]]+)\]\(([^)]+)\)`)
)

func markdownToGemtext(body string) string {
	var out []string
	inFence := false

	for _, line := range strings.Split(strings.ReplaceAll(body, "\r\n", "\n"), "\n") {
		trimmed := strings.TrimSpace(line)
		if strings.HasPrefix(trimmed, "```") {
			inFence = !inFence
			out = append(out, line)
			continue
		}
		if inFence {
			out = append(out, line)
			continue
		}
		if match := standaloneMarkdownLink.FindStringSubmatch(line); match != nil {
			out = append(out, "=> "+match[2]+" "+match[1])
			continue
		}
		if strings.HasPrefix(trimmed, "- ") {
			indent := line[:strings.Index(line, "-")]
			line = indent + "* " + strings.TrimPrefix(trimmed, "- ")
		}
		line = inlineMarkdownLink.ReplaceAllString(line, "$1 ($2)")
		line = strings.ReplaceAll(line, "**", "")
		line = strings.ReplaceAll(line, "__", "")
		out = append(out, line)
	}

	return strings.TrimRight(strings.Join(out, "\n"), "\n") + "\n"
}
