package client

import (
	"encoding/base64"
	"fmt"
	"strings"
)

const maxCameraSnapshotBytes = 2 * 1024 * 1024

func isJPEG(data []byte) bool {
	return len(data) >= 3 && data[0] == 0xff && data[1] == 0xd8 && data[2] == 0xff
}

func encodeCameraSnapshotJPEG(raw []byte) (string, error) {
	if len(raw) < 100 {
		return "", fmt.Errorf("camera capture too small (%d bytes)", len(raw))
	}
	if !isJPEG(raw) {
		return "", fmt.Errorf("camera capture is not JPEG (got %d bytes)", len(raw))
	}
	if len(raw) > maxCameraSnapshotBytes {
		return "", fmt.Errorf("camera image exceeds %d byte cap (%d bytes)", maxCameraSnapshotBytes, len(raw))
	}
	return base64.StdEncoding.EncodeToString(raw), nil
}

// parseDShowVideoDevices extracts quoted DirectShow video device names from ffmpeg -list_devices output.
func parseDShowVideoDevices(stderr string) []string {
	var devs []string
	inVideo := false
	for _, line := range strings.Split(stderr, "\n") {
		lower := strings.ToLower(line)
		if strings.Contains(lower, "directshow video devices") {
			inVideo = true
			continue
		}
		if inVideo && strings.Contains(lower, "directshow audio devices") {
			break
		}
		if !inVideo {
			continue
		}
		if strings.Contains(lower, "alternative name") {
			continue
		}
		name := extractQuotedDeviceName(line)
		if name != "" {
			devs = append(devs, name)
		}
	}
	return devs
}

func extractQuotedDeviceName(line string) string {
	start := strings.Index(line, `"`)
	if start < 0 {
		return ""
	}
	rest := line[start+1:]
	end := strings.Index(rest, `"`)
	if end <= 0 {
		return ""
	}
	return rest[:end]
}
