package build

import (
	"path/filepath"
	"strings"

	"git.akyoto.dev/cli/q/src/build/compiler"
	"git.akyoto.dev/cli/q/src/build/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 parses the input files and generates an executable file.
func (build *Build) Run() (compiler.Result, error) {
	functions, errors := scanner.Scan(build.Files)
	return compiler.Compile(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") {
		return fromFileName(path)
	} else {
		return fromDirectoryName(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"))
}