package build

import (
	"path/filepath"
	"strings"

	"git.akyoto.dev/cli/q/src/compiler"
	"git.akyoto.dev/cli/q/src/config"
	"git.akyoto.dev/cli/q/src/scanner"
)

// Build describes a compiler build.
type Build struct {
	Files []string
}

// New creates a new build.
func New(files ...string) *Build {
	return &Build{
		Files: files,
	}
}

// Run compiles the input files.
func (build *Build) Run() (compiler.Result, error) {
	files, functions, errors := scanner.Scan(build.Files)
	return compiler.Compile(files, functions, errors)
}

// Executable returns the path to the executable.
func (build *Build) Executable() string {
	path, _ := filepath.Abs(build.Files[0])

	if strings.HasSuffix(path, ".q") {
		path = fromFileName(path)
	} else {
		path = fromDirectoryName(path)
	}

	if config.TargetOS == "windows" {
		path += ".exe"
	}

	return path
}

// fromDirectoryName returns the executable path based on the directory name.
func fromDirectoryName(path string) string {
	return filepath.Join(path, filepath.Base(path))
}

// fromFileName returns the executable path based on the file name.
func fromFileName(path string) string {
	return filepath.Join(filepath.Dir(path), strings.TrimSuffix(filepath.Base(path), ".q"))
}