package deploy

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

	"github.com/google/uuid"
)

const agentIDFile = "agent.id"

// EnsureAgentID creates a fresh agent ID during a new embed/install.
func EnsureAgentID(installDir string) (string, error) {
	if err := os.MkdirAll(installDir, 0755); err != nil {
		return "", err
	}
	id := uuid.New().String()
	if err := writeAgentID(installDir, id); err != nil {
		return "", err
	}
	return id, nil
}

// loadOrCreateAgentID reuses an existing agent.id when re-running spread install.
func loadOrCreateAgentID(installDir string) (string, error) {
	if id, err := LoadAgentID(installDir); err == nil && id != "" {
		return id, nil
	}
	return EnsureAgentID(installDir)
}

// LoadAgentID returns the persisted agent ID from the install directory.
func LoadAgentID(installDir string) (string, error) {
	path := filepath.Join(installDir, agentIDFile)
	data, err := os.ReadFile(path)
	if err != nil {
		return "", err
	}
	id := strings.TrimSpace(string(data))
	if id == "" {
		return "", fmt.Errorf("agent id file is empty")
	}
	return id, nil
}

func writeAgentID(installDir, id string) error {
	path := filepath.Join(installDir, agentIDFile)
	return os.WriteFile(path, []byte(id+"\n"), 0600)
}
