//go:build windows

package usbip

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

// FindUsbipExe locates the usbip.exe binary from usbip-win2.
// Checks PATH first, then the standard installation directory.
func FindUsbipExe() (string, error) {
	// Check PATH
	if path, err := exec.LookPath("usbip"); err == nil {
		return path, nil
	}

	// Check standard installation path
	standardPath := filepath.Join(os.Getenv("ProgramFiles"), "USBip", "usbip.exe")
	if _, err := os.Stat(standardPath); err == nil {
		return standardPath, nil
	}

	// Check x86 program files too
	x86Path := filepath.Join(os.Getenv("ProgramFiles(x86)"), "USBip", "usbip.exe")
	if _, err := os.Stat(x86Path); err == nil {
		return x86Path, nil
	}

	return "", fmt.Errorf("usbip.exe nicht gefunden. Bitte usbip-win2 installieren: https://github.com/vadimgrn/usbip-win2/releases")
}

// IsVHCIAvailable checks if usbip-win2 is installed
func IsVHCIAvailable() bool {
	_, err := FindUsbipExe()
	return err == nil
}

// VHCIUnavailableError returns an error describing why VHCI is not available,
// or nil if usbip-win2 is installed and ready.
func VHCIUnavailableError() error {
	if IsVHCIAvailable() {
		return nil
	}
	return fmt.Errorf("usbip-win2 nicht installiert. Der Use-Modus benoetigt den usbip-win2 VHCI-Treiber. Download: https://github.com/vadimgrn/usbip-win2/releases")
}

// DetachDevice detaches a device from the VHCI driver using usbip.exe
func DetachDevice(port int) error {
	usbipExe, err := FindUsbipExe()
	if err != nil {
		return err
	}

	cmd := exec.Command(usbipExe, "detach", "-p", fmt.Sprintf("%d", port))
	output, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("usbip detach failed: %w (output: %s)", err, strings.TrimSpace(string(output)))
	}

	log.Printf("[vhci-win] detached port %d", port)
	return nil
}

// FindFreePort is not used on Windows (usbip.exe selects the port automatically).
// Signature required for cross-platform compilation.
func FindFreePort(speed uint32) (int, error) {
	return -1, fmt.Errorf("not used on Windows - usbip.exe selects port automatically")
}

// AttachDevice is not used on Windows (usbip.exe handles attachment).
// Signature required for cross-platform compilation.
func AttachDevice(port int, sockfd int, devID uint32, speed uint32) error {
	return fmt.Errorf("not used on Windows - use createVHCIAttachment instead")
}
