package openrgb

import (
	"fmt"
	"os/exec"
)

// Client controls RGB devices via the openrgb CLI.
type Client struct {
	bin string
}

func Connect() (*Client, error) {
	bin, err := exec.LookPath("openrgb")
	if err != nil {
		return nil, fmt.Errorf("openrgb not found in PATH: %w", err)
	}

	// Verify openrgb can list devices (confirms it's running/accessible)
	cmd := exec.Command(bin, "--list-devices")
	if out, err := cmd.CombinedOutput(); err != nil {
		return nil, fmt.Errorf("openrgb list-devices failed: %w\n%s", err, out)
	}

	return &Client{bin: bin}, nil
}

func (c *Client) Close() error {
	return nil
}

// SetAllOff sets all devices to black (off) using direct mode.
func (c *Client) SetAllOff() error {
	cmd := exec.Command(c.bin, "--mode", "direct", "--color", "000000")
	if out, err := cmd.CombinedOutput(); err != nil {
		return fmt.Errorf("openrgb set off: %w\n%s", err, out)
	}
	return nil
}

// SetAllOn sets all devices to the given color.
func (c *Client) SetAllOn(r, g, b byte) error {
	color := fmt.Sprintf("%02X%02X%02X", r, g, b)
	cmd := exec.Command(c.bin, "--mode", "direct", "--color", color)
	if out, err := cmd.CombinedOutput(); err != nil {
		return fmt.Errorf("openrgb set on: %w\n%s", err, out)
	}
	return nil
}
