package main

import (
	"bytes"
	"regexp"

	"github.com/yuin/goldmark"
	highlighting "github.com/yuin/goldmark-highlighting"
)

func markdownToHTML(markdownText string) string {
	var buf bytes.Buffer
	md := goldmark.New(
		goldmark.WithExtensions(
			highlighting.NewHighlighting(highlighting.WithStyle("monokai")),
		),
	)
	if err := md.Convert([]byte(markdownText), &buf); err != nil {
		panic(err) // Handle the error appropriately
	}

	return addCopyButtonsToCode(buf.String())
}

func addCopyButtonsToCode(htmlContent string) string {
	buttonHTML := `<button class="copy-button button is-small is-primary is-outlined" onclick="copyToClipboardCode(this)"><i class="fa-solid fa-copy"></i></button>`

	// Regular expression pattern to match <pre> elements and insert the button right before <code>
	pattern := `(<pre[^>]*>)`

	// Compile the regular expression
	re := regexp.MustCompile(pattern)

	// Replace each matched <pre> element with the updated HTML
	updatedHTML := re.ReplaceAllString(htmlContent, "$1"+buttonHTML)

	return updatedHTML
}

func getExistingKeys() (bool, bool, bool, bool, bool, bool) {
	if edgeClient == nil {
		return false, false, false, false, false, false
	}

	var (
		openaiExists    bool
		anthropicExists bool
		mistralExists   bool
		groqExists      bool
		gooseaiExists   bool
		googleExists    bool
	)

	err := edgeClient.QuerySingle(edgeCtx, `
	select exists (
		select global currentUser.setting.keys
		filter .company.name = "openai"
	  );
	`, &openaiExists)
	if err != nil {
		panic(err)
	}

	err = edgeClient.QuerySingle(edgeCtx, `
	select exists (
		select global currentUser.setting.keys
		filter .company.name = "anthropic"
	);
	`, &anthropicExists)
	if err != nil {
		panic(err)
	}

	err = edgeClient.QuerySingle(edgeCtx, `
	select exists (
		select global currentUser.setting.keys
		filter .company.name = "mistral"
	);
	`, &mistralExists)
	if err != nil {
		panic(err)
	}

	err = edgeClient.QuerySingle(edgeCtx, `
	select exists (
		select global currentUser.setting.keys
		filter .company.name = "groq"
	);
	`, &groqExists)
	if err != nil {
		panic(err)
	}

	err = edgeClient.QuerySingle(edgeCtx, `
	select exists (
		select global currentUser.setting.keys
		filter .company.name = "gooseai"
	);
	`, &gooseaiExists)
	if err != nil {
		panic(err)
	}

	err = edgeClient.QuerySingle(edgeCtx, `
	select exists (
		select global currentUser.setting.keys
		filter .company.name = "google"
	);
	`, &googleExists)
	if err != nil {
		panic(err)
	}

	return openaiExists, anthropicExists, mistralExists, groqExists, gooseaiExists, googleExists
}

func Message2RequestMessage(messages []Message) []RequestMessage {
	m := make([]RequestMessage, len(messages))
	for i, msg := range messages {
		var role string
		switch msg.Role {
		case "user":
			role = "user"
		case "bot":
			role = "assistant"
		default:
			role = "system"
		}
		m[i] = RequestMessage{
			Role:    role,
			Content: msg.Content,
		}
	}
	return m
}
