/*
 Copyright 2022 The KubeVela Authors.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 	http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

package main

import (
	"fmt"
	"io"
	"io/fs"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/kubevela/pkg/util/slices"
	"github.com/spf13/cobra"
	"github.com/spf13/cobra/doc"

	"github.com/oam-dev/kubevela/apis/types"
	"github.com/oam-dev/kubevela/references/cli"
)

// PrintCLIByTag print custom defined index
func PrintCLIByTag(cmd *cobra.Command, all []*cobra.Command, tag string) string {
	var result string
	var pl []cli.Printable
	for _, c := range all {
		if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
			continue
		}
		if val, ok := c.Annotations[types.TagCommandType]; !ok || val != tag {
			continue
		}
		cname := cmd.Name() + " " + c.Name()
		link := cname
		link = strings.Replace(link, " ", "_", -1)
		pl = append(pl, cli.NewPrintable(c, fmt.Sprintf("* [%s](%s)\t - %s\n", cname, link, c.Long)))
	}

	slices.Sort(pl, func(i, j cli.Printable) bool { return i.Order < j.Order })

	for _, v := range pl {
		result += v.Desc
	}
	result += "\n"
	return result
}

// GenMarkdownTreeForIndex will generate the Markdown doc for vela index
func GenMarkdownTreeForIndex(cmd *cobra.Command, dir string) error {
	basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".md"
	filename := filepath.Join(dir, basename)
	f, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer f.Close()

	if _, err = io.WriteString(f, "---\ntitle: CLI Commands\n---\n\n\n"); err != nil {
		return err
	}
	for _, tp := range []string{types.TypeStart, types.TypeApp, types.TypeCD, types.TypeExtension, types.TypeSystem} {
		// write header of type
		_, err = io.WriteString(f, "## "+tp+"\n\n")
		if err != nil {
			return err
		}
		str := PrintCLIByTag(cmd, cmd.Commands(), tp)
		// write header of type
		_, err = io.WriteString(f, str)
		if err != nil {
			return err
		}
	}
	_, err = io.WriteString(f, "###### Auto generated by [script in KubeVela](https://github.com/kubevela/kubevela/tree/master/hack/docgen).")
	if err != nil {
		return err
	}
	return nil
}

func main() {

	rootPath := "../kubevela.io/docs/cli/"
	if len(os.Args) > 1 {
		rootPath = os.Args[1]
	}
	fmt.Println("scanning rootPath of CLI docs for replace: ", rootPath)
	vela := cli.NewCommand()
	err := doc.GenMarkdownTree(vela, rootPath)
	if err != nil {
		log.Fatal(err)
	}
	err = GenMarkdownTreeForIndex(vela, rootPath)
	if err != nil {
		log.Fatal("generate docs for vela index fail", err)
	}
	err = filepath.Walk(rootPath, func(path string, info fs.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if info.IsDir() {
			return nil
		}
		data, err := os.ReadFile(path)
		if err != nil {
			return err
		}
		lines := strings.Split(string(data), "\n")
		if len(lines) < 1 {
			return nil
		}

		// check first line to make sure it's autogenerated docs
		firstL := lines[0]
		if !strings.HasPrefix(firstL, "## vela") {
			return nil
		}

		// find the last line and add some link.
		var lastIdx int
		for idx := len(lines) - 1; idx >= 0; idx-- {
			if strings.Contains(lines[idx], "Auto generated") {
				lastIdx = idx
				break
			}
		}
		if lastIdx == 0 {
			return nil
		}
		lines[lastIdx] = "#### Go Back to [CLI Commands](vela) Homepage.\n\n\n###### Auto generated by [spf13/cobra script in KubeVela](https://github.com/kubevela/kubevela/tree/master/hack/docgen)."

		// update the title format
		title := strings.TrimPrefix(firstL, "## ")

		lines[0] = "---"
		newlines := []string{"---", "title: " + title}

		for idx, line := range lines {
			if strings.Contains(line, "[vela](vela.md)") {
				lines[idx] = ""
				continue
			}
			if strings.Contains(line, ".md") && strings.Contains(line, "](") {
				lines[idx] = strings.Replace(line, ".md", "", -1)
			}
		}

		newlines = append(newlines, lines...)
		newcontent := strings.Join(newlines, "\n")
		return os.WriteFile(path, []byte(newcontent), info.Mode())
	})
	if err != nil {
		log.Fatal(err)
	}
}
