// run_unix.go
//go:build !windows
// +build !windows

package spm

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

// Run locates and starts the installed Spitfire browser without waiting for it to exit.
func Run() error {
	installDir, err := GetInstallDir()
	if err != nil {
		return err
	}

	exePath := filepath.Join(installDir, "browser", "spitfire.exe")

	cmd := exec.Command(exePath)
	cmd.Dir = filepath.Join(installDir, "browser")
	return cmd.Start()
}

// RunAndWait locates and starts the installed Spitfire browser and waits for it to exit.
func RunAndWait() error {
	installDir, err := GetInstallDir()
	if err != nil {
		return fmt.Errorf("failed to get install directory: %w", err)
	}

	// Construct the browser executable path
	exePath := filepath.Join(installDir, "browser", "spitfire")
	if _, err := os.Stat(exePath); err != nil {
		return fmt.Errorf("browser executable not found at %s: %w", exePath, err)
	}

	cmd := exec.Command(exePath)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	// Start the process in a new process group
	cmd.SysProcAttr = &syscall.SysProcAttr{
		Setpgid: true,
	}

	fmt.Printf("Starting browser: %s\n", exePath)
	if err := cmd.Start(); err != nil {
		return fmt.Errorf("failed to start browser: %w", err)
	}

	// Print PID and PGID for debugging
	pgid, err := syscall.Getpgid(cmd.Process.Pid)
	if err == nil {
		fmt.Printf("Browser process started with PID %d (PGID %d)\n", cmd.Process.Pid, pgid)
	} else {
		fmt.Printf("Browser process started with PID %d\n", cmd.Process.Pid)
	}

	if err := cmd.Wait(); err != nil {
		return fmt.Errorf("browser exited with error: %w", err)
	}

	fmt.Println("Browser exited successfully.")
	return nil
}