package web

import (
	"bytes"
	"context"
	"html/template"

	"github.com/charmbracelet/soft-serve/git"
	"github.com/charmbracelet/soft-serve/pkg/backend"
	"github.com/charmbracelet/soft-serve/pkg/proto"
	"github.com/microcosm-cc/bluemonday"
	"github.com/yuin/goldmark"
	extension "github.com/yuin/goldmark/extension"
	"github.com/yuin/goldmark/parser"
	goldmarkhtml "github.com/yuin/goldmark/renderer/html"
)

// renderMarkdown converts markdown content to sanitized HTML.
func renderMarkdown(content []byte) (template.HTML, error) {
	var buf bytes.Buffer
	md := goldmark.New(
		goldmark.WithExtensions(extension.GFM),
		goldmark.WithParserOptions(
			parser.WithAutoHeadingID(),
		),
		goldmark.WithRendererOptions(
			goldmarkhtml.WithUnsafe(),
		),
	)

	if err := md.Convert(content, &buf); err != nil {
		return "", err
	}

	policy := bluemonday.UGCPolicy()
	policy.AllowStyling()
	policy.RequireNoFollowOnLinks(false)
	policy.AllowElements("center")
	sanitized := policy.SanitizeBytes(buf.Bytes())

	return template.HTML(sanitized), nil
}

// getServerReadme loads and renders the README from the .soft-serve repository.
func getServerReadme(ctx context.Context, be *backend.Backend) (template.HTML, error) {
	repos, err := be.Repositories(ctx)
	if err != nil {
		return "", err
	}

	for _, r := range repos {
		if r.Name() == ".soft-serve" {
			readme, _, err := backend.Readme(r, nil)
			if err != nil {
				return "", err
			}
			if readme != "" {
				return renderMarkdown([]byte(readme))
			}
		}
	}

	return "", nil
}

// openRepository opens a git repository.
func openRepository(repo proto.Repository) (*git.Repository, error) {
	return repo.Open()
}

// getDefaultBranch returns the default branch name, or empty string if none exists.
func getDefaultBranch(gr *git.Repository) string {
	head, err := gr.HEAD()
	if err != nil || head == nil {
		return ""
	}
	return head.Name().Short()
}
