package main

import (
	"context"
	"embed"
	"errors"
	"fmt"
	"os"

	"git.keks.cloud/kekskurse/wikipress/pkg/wikipress"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"github.com/urfave/cli/v3"
)

//go:embed layout/output.css
var outputcss string

//go:embed layout/src/*.html
var layout embed.FS

func main() {
	log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})

	log.Info().Str("foo", "bar").Msg("Hello world")

	cmd := &cli.Command{
		Name:  "generate",
		Usage: "generate html from git folder",
		Flags: []cli.Flag{
			&cli.StringFlag{
				Name:  "path",
				Value: "content",
				Usage: "Path to the content git repro",
			},
			&cli.StringFlag{
				Name:  "out",
				Value: "./public",
				Usage: "Path to the content git repro",
			},
			&cli.BoolFlag{
				Name:  "no-git",
				Value: false,
				Usage: "dont use git, just current state",
			},
		},
		Action: action,
	}

	if err := cmd.Run(context.Background(), os.Args); err != nil {
		log.Fatal().Err(err).Msg("Error wile generate Page")
	}
}

func action(ctx context.Context, cmd *cli.Command) error {
	if _, err := os.Stat(cmd.String("out")); !os.IsNotExist(err) {
		log.Warn().Msg("Remove out folder")
		os.RemoveAll(cmd.String("out"))
	}
	os.MkdirAll(cmd.String("path"), 0755)
	var files []wikipress.File
	var err error
	if cmd.Bool("no-git") {
		files, err = wikipress.ListFilesFromHDD(cmd.String("path"))
		if err != nil {
			return err
		}
	} else {
		files, err = wikipress.ListFilesFromGitRepro(cmd.String("path"))
		if err != nil {
			return err
		}
	}

	menu := wikipress.GenerateMenu(files)

	for _, file := range files {
		log.Debug().Str("file", file.Name).Msg("Generate Page")
		// Copy not mark down files
		if file.GetExtension() != "md" {
			err = wikipress.CreateFilePageAndCopyContent(file, cmd.String("out"))
			if err != nil {
				return fmt.Errorf("%w: %s", errors.New("cant create file page and copy content"), err)
			}
			err = os.Symlink(fmt.Sprintf("./%v_%v.%v", file.GetName(), file.GetLastVersion().Hash, file.GetExtension()), fmt.Sprintf("%v/%v/%v.%v", cmd.String("out"), file.GetFolder(), file.GetName(), file.GetExtension()))
			if err != nil {
				return err
			}
			// TODO: Copy and create media page
			continue
		}

		err = wikipress.GenerateHTMLPageForMarkedown(file, menu, cmd.String("out"), layout)
		if err != nil {
			return err
		}

		err = os.Symlink(fmt.Sprintf("./%v_%v.html", file.GetName(), file.GetLastVersion().Hash), fmt.Sprintf("%v/%v/%v.html", cmd.String("out"), file.GetFolder(), file.GetName()))
		if err != nil {
			return err
		}
	}

	err = os.WriteFile(cmd.String("out")+"/output.css", []byte(outputcss), 0644)
	if err != nil {
		return err
	}

	return nil
}
