package new

import (
	"fes/modules/config"
	"fes/modules/ui"
	"fmt"
	"os"
	"os/exec"
	"os/user"
	"path/filepath"
	"strings"
)

/* try to get git user, if not system user */
func getName() string {
	out, err := exec.Command("git", "config", "user.name").Output()
	if err == nil {
		s := strings.TrimSpace(string(out))
		if s != "" {
			return s
		}
	}
	u, err := user.Current()
	if err == nil && u.Username != "" {
		return u.Username
	}
	return "unknown"
}

/* helper function for writing files */
func write(path string, format string, args ...any) error {
	dir := filepath.Dir(path)
	if err := os.MkdirAll(dir, 0755); err != nil {
		panic(err)
	}
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	_, err = fmt.Fprintf(f, format, args...)
	return err
}

/* creates a hello world project */
func Project(dir string) error {
	if err := os.Mkdir(dir, 0755); err != nil {
		return err
	}
	if err := os.Chdir(dir); err != nil {
		return err
	}

	if *config.Docker {
		write("docker-compose.yml", `services:
  %s:
    image: git.vxserver.dev/fsd/fes:latest
    ports:
      - "3000:3000"
    volumes:
      - ./app:/app`, dir)
		if err := os.Mkdir("app", 0755); err != nil {
			return err
		}
		if err := os.Chdir("app"); err != nil {
			return err
		}
	}

	name := getName()

	write("www/index.lua", `local fes = require("fes")
local site = fes.fes()

-- site.copyright = fes.util.copyright("https://example.com", "%s")

site:h1("Hello, World!")

return site`, name)
	write("Fes.toml", `[app]

name = "%s"
version = "0.0.1"
authors = ["%s"]`, dir, name)
	write("README.md", strings.ReplaceAll(`# %s

$$$$$$
fes new %s
$$$$$$

> **Know what you are doing?** Delete this file. Have fun!

## Project Structure

Inside your Fes project, you'll see the following directories and files:

$$$$$$
.
├── Fes.toml
├── README.md
└── www
    └── index.lua
$$$$$$

Fes looks for $$.lua$$ files in the $$www/$$ directory. Each file is exposed as a route based on its file name.

## Commands

All commands are run from the root of the project, from a terminal:

| Command                   | Action                                           |
| :------------------------ | :----------------------------------------------- |
| $$fes run .$$               | Runs the project at $$.$$                          |

## What to learn more?

Check out [Fes's docs](https://docs.vxserver.dev/static/fes.html).`, "$$", "`"), dir, dir)

	ui.Hint("you can run this with `fes run %s`", dir)

	fmt.Println("Created new Fes project at", func() string {
		if cwd, err := os.Getwd(); err != nil {
			return dir
		} else {
			return cwd
		}
	}())

	return nil
}
