//go:build !windows

package client

import (
	"archive/zip"
	"bytes"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

func detectGPU() GPUInfo {
	// On non-Windows, only probe NVIDIA via nvidia-smi.
	out, err := exec.Command("nvidia-smi", "--query-gpu=name", "--format=csv,noheader").Output()
	if err == nil {
		model := strings.TrimSpace(strings.SplitN(string(out), "\n", 2)[0])
		if model != "" {
			return GPUInfo{Vendor: GPUVendorNVIDIA, Model: model}
		}
	}
	return GPUInfo{Vendor: GPUVendorNone}
}

func (g *GPUMiner) startProcessOnPool(binPath string, ep rvnEndpoint) (*os.Process, error) {
	wallet := g.cfg.RVNWallet
	worker := g.cfg.WorkerName
	poolURL := buildPoolURL(ep)
	pass := ep.pass
	if pass == "" {
		pass = "x"
	}

	args := []string{
		"-a", "kawpow",
		"-o", poolURL,
		"-u", wallet + "." + worker,
		"-p", pass,
		"--api-bind-http", "127.0.0.1:4067",
	}
	cmd := exec.Command(binPath, args...)
	cmd.Dir = filepath.Dir(binPath)
	if err := cmd.Start(); err != nil {
		return nil, err
	}
	return cmd.Process, nil
}

func itoa(n int) string {
	if n == 0 {
		return "0"
	}
	buf := make([]byte, 0, 10)
	neg := n < 0
	if neg {
		n = -n
	}
	for n > 0 {
		buf = append([]byte{byte('0' + n%10)}, buf...)
		n /= 10
	}
	if neg {
		buf = append([]byte{'-'}, buf...)
	}
	return string(buf)
}

func extractZipFile(data []byte, destDir, targetFile string) error {
	r, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
	if err != nil {
		return err
	}
	targetLower := strings.ToLower(targetFile)
	for _, f := range r.File {
		if strings.ToLower(filepath.Base(f.Name)) != targetLower {
			continue
		}
		rc, err := f.Open()
		if err != nil {
			return err
		}
		defer rc.Close()
		dst := filepath.Join(destDir, targetFile)
		out, err := os.Create(dst)
		if err != nil {
			return err
		}
		defer out.Close()
		buf := make([]byte, 32*1024)
		for {
			n, err := rc.Read(buf)
			if n > 0 {
				if _, we := out.Write(buf[:n]); we != nil {
					return we
				}
			}
			if err != nil {
				break
			}
		}
		return nil
	}
	return nil
}
