package server

import (
	"github.com/gomarkdown/markdown"
	"github.com/gomarkdown/markdown/html"
	"github.com/gomarkdown/markdown/parser"
	"regexp"
	"strings"
)

func joinBase(base, name string) string {
	if base == "" {
		return "/" + name
	}
	return base + "/" + name
}

func basePath(base string) string {
	if base == "" || base == "." {
		return "/"
	}
	return base
}

func fixMalformedToml(content string) string {
	re := regexp.MustCompile(`(?m)^(\s*\w+\s*=\s*)$`)
	return re.ReplaceAllStringFunc(content, func(match string) string {
		parts := strings.Split(strings.TrimSpace(match), "=")
		if len(parts) == 2 && strings.TrimSpace(parts[1]) == "" {
			key := strings.TrimSpace(parts[0])
			return key + " = \"\""
		}
		return match
	})
}

func markdownToHTML(mdText string) string {
	extensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock
	p := parser.NewWithExtensions(extensions)
	doc := p.Parse([]byte(mdText))
	htmlFlags := html.CommonFlags | html.HrefTargetBlank
	opts := html.RendererOptions{Flags: htmlFlags}
	renderer := html.NewRenderer(opts)
	return string(markdown.Render(doc, renderer))
}
