//go:build windows

package deploy

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

// StartCloudflaredTunnel launches cloudflared pointing at serverURL (background).
func StartCloudflaredTunnel(serverURL string) (string, error) {
	serverURL = strings.TrimSpace(serverURL)
	if serverURL == "" {
		return "", fmt.Errorf("server URL required")
	}

	if err := HiddenRun("cloudflared", "--version"); err != nil {
		output, dlErr := HiddenCombinedOutput("powershell", "-NoProfile", "-WindowStyle", "Hidden", "-Command",
			"Invoke-WebRequest -Uri https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe -OutFile $env:TEMP\\cloudflared.exe")
		if dlErr != nil {
			return string(output), fmt.Errorf("cloudflared not found and download failed: %w", dlErr)
		}
		src := filepath.Join(os.Getenv("TEMP"), "cloudflared.exe")
		dst := filepath.Join(os.Getenv("SYSTEMROOT"), "System32", "cloudflared.exe")
		_ = HiddenRun("copy", "/Y", src, dst)
	}

	cmd := HiddenCommand("cloudflared", "tunnel", "--url", serverURL)
	if err := cmd.Start(); err != nil {
		return "", fmt.Errorf("failed to start cloudflared: %w", err)
	}
	return fmt.Sprintf("cloudflared tunnel started (pid %d) -> %s", cmd.Process.Pid, serverURL), nil
}
