package apt

import (
	"fmt"
	"os"
	"os/exec"
	"os/user"
)

// CheckPermissions verifies that we can run apt (either as root or with sudo)
func CheckPermissions() error {
	// Check if apt is available
	if _, err := exec.LookPath("apt"); err != nil {
		return fmt.Errorf("apt not found - this tool requires apt package manager")
	}

	// Check if running as root
	currentUser, err := user.Current()
	if err != nil {
		return fmt.Errorf("could not determine current user: %w", err)
	}

	if currentUser.Uid == "0" {
		// Running as root, we're good
		return nil
	}

	// Not root, check if sudo is available
	if _, err := exec.LookPath("sudo"); err != nil {
		return fmt.Errorf("not running as root and sudo not available - please run with sudo or as root")
	}

	return nil
}

// InstallDeb installs a .deb package using apt
func InstallDeb(debFile string) error {
	// Verify the file exists
	if _, err := os.Stat(debFile); os.IsNotExist(err) {
		return fmt.Errorf("deb file does not exist: %s", debFile)
	}

	// Check if we're running as root
	currentUser, err := user.Current()
	if err != nil {
		return fmt.Errorf("could not determine current user: %w", err)
	}

	var cmd *exec.Cmd
	if currentUser.Uid == "0" {
		// Running as root
		cmd = exec.Command("apt", "install", "-y", debFile)
	} else {
		// Use sudo
		cmd = exec.Command("sudo", "apt", "install", "-y", debFile)
	}

	// Set up command to stream output to user
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Stdin = os.Stdin // Allow user interaction if needed (like password prompt)

	// Run the command
	if err := cmd.Run(); err != nil {
		if exitError, ok := err.(*exec.ExitError); ok {
			return fmt.Errorf("apt install failed with exit code %d", exitError.ExitCode())
		}
		return fmt.Errorf("failed to run apt install: %w", err)
	}

	return nil
}

// UpdatePackageList updates the apt package list
func UpdatePackageList() error {
	currentUser, err := user.Current()
	if err != nil {
		return fmt.Errorf("could not determine current user: %w", err)
	}

	var cmd *exec.Cmd
	if currentUser.Uid == "0" {
		cmd = exec.Command("apt", "update")
	} else {
		cmd = exec.Command("sudo", "apt", "update")
	}

	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	return cmd.Run()
}
