package provision

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"

	"zlh-agent/internal/state"
)

/*
   ensureDir makes sure the destination directory exists.
*/
func ensureDir(path string) error {
	return os.MkdirAll(path, 0755)
}

/*
   downloadFile downloads a file from URL → destination path.
*/
func downloadFile(url, dest string) error {
	if err := ensureDir(filepath.Dir(dest)); err != nil {
		return fmt.Errorf("mkdir: %w", err)
	}

	resp, err := http.Get(url)
	if err != nil {
		return fmt.Errorf("download %s: %w", url, err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("download %s: http %s", url, resp.Status)
	}

	out, err := os.Create(dest)
	if err != nil {
		return fmt.Errorf("create %s: %w", dest, err)
	}
	defer out.Close()

	if _, err := io.Copy(out, resp.Body); err != nil {
		return fmt.Errorf("write %s: %w", dest, err)
	}

	return nil
}

/*
   DownloadArtifact is a small wrapper that:

   - resolves relative paths with buildArtifactURL()
   - downloads to "dest"
*/
func DownloadArtifact(cfg state.Config, relativeOrFullURL, dest string) error {
	url := buildArtifactURL(relativeOrFullURL)
	return downloadFile(url, dest)
}
