package paths

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

// DataDir returns the data directory for chirami.
// Priority:
// 1. $CHIRAMI_DATA
// 2. macOS: ~/Library/Application Support/chirami
// 3. Linux/others: $XDG_DATA_HOME/chirami or ~/.local/share/chirami
func DataDir() string {
	if v := os.Getenv("CHIRAMI_DATA"); v != "" {
		return v
	}
	home, err := os.UserHomeDir()
	if err != nil {
		home = "."
	}
	if runtime.GOOS == "darwin" {
		return filepath.Join(home, "Library", "Application Support", "chirami")
	}
	if v := os.Getenv("XDG_DATA_HOME"); v != "" {
		return filepath.Join(v, "chirami")
	}
	return filepath.Join(home, ".local", "share", "chirami")
}

// OpenURL opens url in the default system browser detached.
// On macOS it uses "open", on Linux/others it uses "xdg-open".
// It reaps the process in a background goroutine.
func OpenURL(url string) error {
	bin := "xdg-open"
	if runtime.GOOS == "darwin" {
		bin = "open"
	}
	cmd := exec.Command(bin, url)
	if err := cmd.Start(); err != nil {
		return err
	}
	go func() {
		_ = cmd.Wait()
	}()
	return nil
}
