package executor

import (
	"bufio"
	"context"
	"os/exec"

	"deployment-manager/internal/events"
)

func RunCmd(ctx context.Context, eventChan chan<- *events.Event, repoID int64, cmd string, args ...string) error {
	c := exec.CommandContext(ctx, cmd, args...)

	stdout, _ := c.StdoutPipe()
	stderr, _ := c.StderrPipe()

	if err := c.Start(); err != nil {
		return err
	}

	go stream(stdout, eventChan, repoID, "stdout")
	go stream(stderr, eventChan, repoID, "stderr")

	return c.Wait()
}

func stream(r interface{ Read([]byte) (int, error) }, eventChan chan<- *events.Event, repoID int64, streamType string) {
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		event := events.NewLogEvent(repoID, scanner.Text())
		event.Data["stream"] = streamType
		eventChan <- event
	}
}
