package main

import (
	"embed"
	"flag"
	"fmt"
	"os"
	"runtime"

	"github.com/fatih/color"

	"fes/modules/config"
	"fes/modules/doc"
	"fes/modules/new"
	"fes/modules/server"
	"fes/modules/ui"
	"fes/modules/version"
)

//go:embed lib/*
var lib embed.FS

//go:embed index.html
var documentation string

func init() {
	config.Port = flag.Int("p", 3000, "Set the server port")
	config.Color = flag.Bool("no-color", false, "Disable color output")
	config.Static = flag.Bool("static", false, "Render and save all pages")
	config.Docker = flag.Bool("docker", false, "Create a docker project")
	config.Lib = lib
	config.Doc = documentation
	config.Verbose = flag.Bool("verbose", false, "Enable verbose logging")
}

func main() {
	var m runtime.MemStats

	flag.Usage = func() {
		fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s [options] <command> <project_dir>\n", os.Args[0])
		fmt.Fprintln(flag.CommandLine.Output(), "Commands:")
		fmt.Fprintln(flag.CommandLine.Output(), "  new <project_dir>   Create a new project")
		fmt.Fprintln(flag.CommandLine.Output(), "  doc                 Open documentation")
		fmt.Fprintln(flag.CommandLine.Output(), "  run <project_dir>   Start the server")
		fmt.Fprintln(flag.CommandLine.Output(), "Options:")
		flag.PrintDefaults()
		fmt.Fprintln(flag.CommandLine.Output(), "For bug reports, contact a developer and describe the issue. Provide the output of the `-V1` flag.")
	}

	showVersion := flag.Bool("version", false, "Show version and exit")
	showFullVersion := flag.Bool("V1", false, "Show extended version information and exit")

	flag.Parse()

	if *showVersion {
		version.Version()
	}

	if *showFullVersion {
		version.FullVersion()
	}

	if *config.Color {
		color.NoColor = true
	}

	args := flag.Args()
	if len(args) < 1 {
		flag.Usage()
		os.Exit(1)
	}

	cmd := args[0]
	var dir string
	if cmd == "new" || cmd == "run" {
		if len(args) < 2 {
			fmt.Fprintf(os.Stderr, "Error: %s requires <project_dir>\n", cmd)
			flag.Usage()
			os.Exit(1)
		}
		dir = args[1]
	}

	switch cmd {
	case "new":
		if err := new.Project(dir); err != nil {
			fmt.Fprintln(os.Stderr, "Error:", err)
			os.Exit(1)
		}
	case "doc":
		if err := doc.Open(); err != nil {
			fmt.Fprintln(os.Stderr, "Error:", err)
			os.Exit(1)
		}
	case "run":
		if *config.Port == 3000 {
			ui.WARNING("Using default port, this may lead to conflicts with other services")
		}
		ui.Log("Fes is starting")
		ui.Log("Fes version=%s, commit=%s, just started", version.VERSION, version.GetCommit())

		runtime.ReadMemStats(&m)
		ui.Log("FRE memory usage when created %v Mb", m.TotalAlloc/1024/1024)

		server.Start(dir)
	default:
		fmt.Fprintf(os.Stderr, "Unknown command: %s\n", cmd)
		flag.Usage()
		os.Exit(1)
	}
}
