package mage_helpers

import (
	"fmt"
	"os"
	"os/exec"
	"path"
	"runtime"
	"strings"

	"github.com/magefile/mage/sh"
)

func Clean(path string) error {

	cmd := exec.Command("rm", "-rf", "build")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Dir = path
	err := cmd.Run()
	if err != nil {
		return err
	}

	cmd = exec.Command("mkdir", "-p", "build")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Dir = path
	err = cmd.Run()
	if err != nil {
		return err
	}
	return nil
}

func Build(dir string, module string, isDebug bool) error {
	currentDir, _ := os.Getwd()
	fullPath := currentDir + "/core/" + dir

	if err := Clean(fullPath); err != nil {
		return err
	}

	handler := path.Base(fullPath)
	fmt.Println(fmt.Sprintf("Building %v", handler))

	outputDir := fmt.Sprintf(currentDir+`/core/build/handlers/%v`, handler)
	outputFile := fmt.Sprintf(`%v/%v`, outputDir, handler)
	appPath := fmt.Sprintf(`%v/core/%v`, module, handler)
	err := BuildGolangApp(outputFile, appPath, module, isDebug)
	if err != nil {
		return err
	}

	// Copy files in handler folder
	err = copyFilesToBuildDir(fullPath, outputDir)
	if err != nil {
		return err
	}

	// Copy shared files
	sharedDir := currentDir + "/core/utils"
	_, err = os.Stat(sharedDir)
	if err == nil {
		err = copyFilesToBuildDir(sharedDir, outputDir)
		if err != nil {
			return err
		}
	}

	if isDebug {
		// copy env file
		err = copyFilesToBuildDir(currentDir+"/.env.debug", outputDir)
		if err != nil {
			return err
		}
	}

	return nil
}

func BuildGolangApp(outputDir string, appPath string, module string, isDebug bool) error {
	commandArgs := []string{
		`build`,
		fmt.Sprintf(`-ldflags=-X %v/globals.BuildVersion=%v -X %v/globals.OSType=%v -X %v/globals.IsDebugBuild=%v`, module, CurrentCommit(), module, runtime.GOOS, module, isDebug),
	}

	if isDebug {
		commandArgs = append(commandArgs, "-gcflags", "all=-N -l")
	}

	commandArgs = append(commandArgs, `-o`,
		outputDir,
		appPath)

	env := map[string]string{
		"GOOS": "linux",
	}

	if !isDebug {
		if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" { // M1 mac
			// Change to intel architecture (used when deploying locally)
			env["GOARCH"] = "amd64"
		}
	}

	err := sh.RunWith(env, "go", commandArgs...)
	if err != nil {
		return err
	}
	return nil
}

func BuildGolangAppWindows(outputDir string, appPath string, module string, isDebug bool) error {
	commandArgs := []string{
		`build`,
		fmt.Sprintf(`-ldflags=-X %v/globals.BuildVersion=%v -X %v/globals.OSType=%v -X %v/globals.IsDebugBuild=%v`, module, CurrentCommit(), module, runtime.GOOS, module, isDebug),
	}

	if isDebug {
		commandArgs = append(commandArgs, "-gcflags", "all=-N -l")
	}

	commandArgs = append(commandArgs, `-o`,
		outputDir,
		appPath)

	env := map[string]string{
		"GOOS":   "windows",
		"GOARCH": "amd64",
	}

	err := sh.RunWith(env, "go", commandArgs...)
	if err != nil {
		return err
	}
	return nil
}

func BuildMJML(filename string) error {
	// Get the full path to the file
	currentDir, _ := os.Getwd()
	fullFilePath := currentDir + "/" + filename
	fmt.Println(fullFilePath)

	// Trim the extension from the filename
	if strings.HasSuffix(fullFilePath, ".mjml") {
		fullFilePath = strings.TrimSuffix(fullFilePath, ".mjml")
	}

	commandArgs := []string{
		"-l strict",
		"--config.beautify=true",
		fmt.Sprintf("-r %v.mjml", fullFilePath),
		fmt.Sprintf("-o%v.html", fullFilePath),
	}

	err := sh.RunWith(nil, "mjml", commandArgs...)
	if err != nil {
		return err
	}
	return nil

}