package main

import (
	"embed"
	"errors"
	"flag"
	"fmt"
	"os"

	"github.com/fatih/color"

	"fes/src/config"
	"fes/src/doc"
	"fes/src/new"
	"fes/src/server"
)

//go:embed core/*
var core 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.Core = core
	config.Doc = documentation
}

func main() {
	flag.Usage = func() {
		fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s [options] <command> <project_dir>\n", os.Args[0])
		fmt.Println("Commands:")
		fmt.Println("  new <project_dir>   Create a new project")
		fmt.Println("  doc                 Open documentation")
		fmt.Println("  run <project_dir>   Start the server")
		fmt.Println("Options:")
		flag.PrintDefaults()
	}
	flag.Parse()

	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 err := server.Start(dir); err != nil {
			if errors.Is(err, os.ErrNotExist) {
				fmt.Fprintf(os.Stderr, "%s does not exist\n", dir)
				fmt.Fprintf(os.Stderr, "Try: fes new %s\n", dir)
				os.Exit(1)
			} else {
				fmt.Fprintln(os.Stderr, "Error:", err)
				os.Exit(1)
			}
		}
	default:
		fmt.Fprintf(os.Stderr, "Unknown command: %s\n", cmd)
		flag.Usage()
		os.Exit(1)
	}
}
