package spitfire

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
)

// CheckSystemDependencies ensures that required tools for building are installed.
func CheckSystemDependencies() error {
	requiredTools := map[string]string{
		"git":     "https://git-scm.com/download/win",     // Git
		"python":  "https://www.python.org/downloads/",    // Python
		"pip3":    "https://pip.pypa.io/en/stable/installing/", // Pip3
	}

	if runtime.GOOS == "windows" {
		// Check for MozillaBuild installation
		mozBuildPath := os.Getenv("MOZILLABUILD")
		if mozBuildPath == "" {
			mozBuildPath = "C:\\mozilla-build" // Default to standard MozillaBuild path
		}

		// Check if MozillaBuild exists at the specified location
		if !dirExists(mozBuildPath) {
			requiredTools["mozbuild"] = "https://ftp.mozilla.org/pub/mozilla/libraries/win32/MozillaBuildSetup-Latest.exe"
		}
	}

	missingTools := []string{}

	// Check for each required tool
	for tool, downloadLink := range requiredTools {
		if !isCommandAvailable(tool) {
			missingTools = append(missingTools, fmt.Sprintf("%s (Download: %s)", tool, downloadLink))
		}
	}

	// Special check for mach in the local source directory (mozilla-central)
	machPath := filepath.Join("mozilla-central", "mach")
	if !fileExists(machPath) {
		missingTools = append(missingTools, fmt.Sprintf("mach (run from mozilla-central directory)"))
	}

	if len(missingTools) > 0 {
		fmt.Println("The following tools are missing and are required for the build:")
		for _, tool := range missingTools {
			fmt.Println(" - " + tool)
		}
		return fmt.Errorf("missing required tools")
	}

	fmt.Println("All required system dependencies are installed.")
	return nil
}

// isCommandAvailable checks if a command/tool is available on the system.
func isCommandAvailable(command string) bool {
	_, err := exec.LookPath(command)
	return err == nil
}

// fileExists checks if a file exists at the given path.
func fileExists(path string) bool {
	_, err := os.Stat(path)
	return err == nil
}

// dirExists checks if a directory exists at the given path.
func dirExists(path string) bool {
	info, err := os.Stat(path)
	if os.IsNotExist(err) {
		return false
	}
	return info.IsDir()
}