package main

import (
	"os"
	"path/filepath"
	"strings"

	"github.com/spf13/cobra"
)

// MarkdownPostProcessing goes through the generated files
func MarkdownPostProcessing(cmd *cobra.Command, dir string, processor func(string) string) error {
	for _, c := range cmd.Commands() {
		if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
			continue
		}
		if err := MarkdownPostProcessing(c, dir, processor); err != nil {
			return err
		}
	}

	basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".md"
	filename := filepath.Join(dir, basename)

	// Remove the markdown file for the version subcommand
	if strings.Contains(basename, "version") {
		return os.Remove(filename)
	}

	markdownBytes, err := os.ReadFile(filename)
	if err != nil {
		return err
	}

	processedMarkDown := processor(string(markdownBytes))

	return os.WriteFile(filename, []byte(processedMarkDown), 0600)
}

// cleanupForInclude parts of markdown that will make difficult to use it as include in the website:
// - The section before synopsis.
// - The sections see also.
func cleanupForInclude(md string) string {
	lines := strings.Split(md, "\n")

	// add title for component docs
	firstL := lines[0]
	title := strings.TrimPrefix(firstL, "## ")
	lines[0] = "---"
	newlines := []string{"---", "title: " + title}
	newlines = append(newlines, lines...)

	cleanMd := ""
	for i, line := range newlines {
		if line == "### SEE ALSO" {
			break
		}

		cleanMd += line
		if i < len(newlines)-1 {
			cleanMd += "\n"
		}
	}

	cleanMd += "###### Auto generated by [spf13/cobra script in Karmada](https://github.com/karmada-io/karmada/tree/master/hack/tools/gencomponentdocs)"
	return cleanMd
}
