package dashboard

import (
	"io/fs"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"

	"github.com/tidbcloud/AgentTeam/desktop/docs"
)

// HelpDocsHandler serves embedded help documentation.
type HelpDocsHandler struct{}

// NewHelpDocsHandler creates a new HelpDocsHandler.
func NewHelpDocsHandler() gin.HandlerFunc {
	return (&HelpDocsHandler{}).Handle
}

// Handle returns the list of available help documents for a given locale,
// or the content of a specific document.
//
// GET /help-docs?locale=en          -> list of document names
// GET /help-docs?locale=en&doc=overview -> content of overview.md
func (h *HelpDocsHandler) Handle(c *gin.Context) {
	locale := c.Query("locale")
	if locale == "" {
		locale = "en"
	}

	// Only allow known locales
	if locale != "en" && locale != "zh" {
		locale = "en"
	}

	docName := c.Query("doc")

	fsys, err := docs.FS()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "docs not available"})
		return
	}

	localeDir := locale

	if docName != "" {
		// Serve specific document content
		// Sanitize: only allow alphanumeric, hyphens, underscores
		clean := strings.Map(func(r rune) rune {
			if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
				return r
			}
			return -1
		}, docName)

		if clean != docName {
			c.JSON(http.StatusBadRequest, gin.H{"error": "invalid doc name"})
			return
		}

		path := localeDir + "/" + clean + ".md"
		data, err := fs.ReadFile(fsys, path)
		if err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": "document not found"})
			return
		}

		c.Data(http.StatusOK, "text/markdown; charset=utf-8", data)
		return
	}

	// List available documents
	entries, err := fs.ReadDir(fsys, localeDir)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read docs"})
		return
	}

	docs := make([]string, 0, len(entries))
	for _, e := range entries {
		if e.IsDir() || !strings.HasSuffix(e.Name(), ".md") {
			continue
		}
		name := strings.TrimSuffix(e.Name(), ".md")
		docs = append(docs, name)
	}

	c.JSON(http.StatusOK, gin.H{"docs": docs})
}
