// Copyright 2021 The Witness Contributors
//
// 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 (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/in-toto/witness/cmd"
	"github.com/invopop/jsonschema"
	"github.com/spf13/cobra/doc"

	_ "github.com/in-toto/go-witness"
	"github.com/in-toto/go-witness/attestation"
)

var directory string

func init() {
	flag.StringVar(&directory, "dir", "docs", "Directory to store the generated docs")
	flag.Parse()
}

func main() {
	log.Println("Generating CLI Reference documentation")
	mdContent := "# Witness CLI Reference\n\nThis is the reference for the Witness command line tool, generated by [Cobra](https://cobra.dev/).\n\n"
	// Generate markdown content for all commands
	for _, command := range cmd.New().Commands() {
		// We are not generating docs for the completion command right now, as it doesn't render in Markdown correctly
		if command.Use == "completion [bash|zsh|fish|powershell]" {
			continue
		}

		buf := new(bytes.Buffer)
		err := doc.GenMarkdown(command, buf)
		if err != nil {
			fmt.Println("Error generating markdown for command:", command.Use)
			continue
		}
		mdContent += buf.String()
	}

	// Write the combined markdown content to a file
	err := os.WriteFile(fmt.Sprintf("%s/commands.md", directory), []byte(mdContent), 0644)
	if err != nil {
		fmt.Println("Error writing to file:", err)
		os.Exit(1)
	}

	log.Println("Documentation generated successfully")

	entries := attestation.RegistrationEntries()
	for _, entry := range entries {
		att := entry.Factory()
		schema := att.Schema()
		schemaJson, err := schema.MarshalJSON()
		if err != nil {
			fmt.Println("Error marshalling JSON schema:", err)
			os.Exit(1)
		}

		var indented bytes.Buffer
		err = json.Indent(&indented, schemaJson, "", "  ")
		if err != nil {
			fmt.Println("Error marshalling JSON schema:", err)
			os.Exit(1)
		}

		schemaContent := "## Schema" + "\n```json\n" + indented.String() + "\n```\n"
		err = os.WriteFile(fmt.Sprintf("%s/attestors/%s.json", directory, att.Name()), []byte(indented.String()+"\n "), 0644)
		if err != nil {
			fmt.Println("Error writing to file:", err)
			os.Exit(1)
		}
		log.Printf("Schema for %s written to %s/attestors/%s.json\n", att.Name(), directory, att.Name())
		f, err := os.ReadFile(fmt.Sprintf("%s/attestors/%s.md", directory, att.Name()))
		if err != nil {
			fmt.Println("Error reading file:", err)
			os.Exit(1)
		}

		// Find the index of "## Schema" string
		index := strings.Index(string(f), "## Schema")
		if index == -1 {
			f = append(f, schemaContent...)

			err = os.WriteFile(fmt.Sprintf("%s/attestors/%s.md", directory, att.Name()), f, 0644)
			if err != nil {
				fmt.Println("Error writing to file:", err)
				os.Exit(1)
			}
			continue
		}

		// Truncate the content to remove everything after "## Schema"
		f = f[:index]

		f = append(f, schemaContent...)

		err = os.WriteFile(fmt.Sprintf("%s/attestors/%s.md", directory, att.Name()), f, 0644)
		if err != nil {
			fmt.Println("Error writing to file:", err)
			os.Exit(1)
		}

		log.Printf("Schema for %s written to %s/attestors/%s.md\n", att.Name(), directory, att.Name())

	}

	log.Println("Generating schema for the Witness Collection")
	coll := jsonschema.Reflect(attestation.Collection{})
	schemaJson, err := coll.MarshalJSON()
	if err != nil {
		fmt.Println("Error marshalling JSON schema:", err)
		os.Exit(1)
	}
	var indented bytes.Buffer
	err = json.Indent(&indented, schemaJson, "", "  ")
	if err != nil {
		fmt.Println("Error marshalling JSON schema:", err)
		os.Exit(1)
	}
	schemaContent := "## Schema" + "\n```json\n" + indented.String() + "\n```\n"
	f, err := os.ReadFile(fmt.Sprintf("%s/concepts/collection.md", directory))
	if err != nil {
		fmt.Println("Error reading file:", err)
		os.Exit(1)
	}

	// Find the index of "## Schema" string
	index := strings.Index(string(f), "## Schema")
	if index == -1 {
		f = append(f, schemaContent...)

		err = os.WriteFile(fmt.Sprintf("%s/concepts/collection.md", directory), f, 0644)
		if err != nil {
			fmt.Println("Error writing to file:", err)
			os.Exit(1)
		}
	} else {

		// Truncate the content to remove everything after "## Schema"
		f = f[:index]

		f = append(f, schemaContent...)

		err = os.WriteFile(fmt.Sprintf("%s/concepts/collection.md", directory), f, 0644)
		if err != nil {
			fmt.Println("Error writing to file:", err)
			os.Exit(1)
		}

		log.Printf("Schema for collection written to %s/concepts/collection.md\n", directory)
	}
}
