// Package restore provides functionality for restoring ZFS snapshots from a backup server.
// It supports restoring to ZFS datasets, saving to files, and mounting restored datasets.
package restore

import (
	"bufio"
	"os"
	"strings"
)

// Config holds restore client configuration.
type Config struct {
	// ClientID is the unique identifier for this client
	ClientID string
	// APIKey is the authentication key for the server
	APIKey string
	// ServerURL is the base URL of the backup server
	ServerURL string
}

// LoadConfig loads restore client configuration from environment variables and .env file.
// Environment variables take precedence over .env file values.
func LoadConfig() *Config {
	// Load .env file if exists
	loadEnvFile(".env")

	return &Config{
		ClientID:  getEnv("CLIENT_ID", "client1"),
		APIKey:    getEnv("API_KEY", "secret123"),
		ServerURL: getEnv("SERVER_URL", "http://localhost:8080"),
	}
}

// loadEnvFile loads key=value pairs from a .env file.
// Lines starting with # are treated as comments.
// Values can be quoted or unquoted.
func loadEnvFile(filename string) {
	file, err := os.Open(filename)
	if err != nil {
		return // .env file is optional
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())

		// Skip empty lines and comments
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}

		// Parse key=value
		parts := strings.SplitN(line, "=", 2)
		if len(parts) != 2 {
			continue
		}

		key := strings.TrimSpace(parts[0])
		value := strings.TrimSpace(parts[1])

		// Remove quotes if present
		if len(value) >= 2 && (value[0] == '"' || value[0] == '\'') {
			value = value[1 : len(value)-1]
		}

		// Only set if not already defined in environment
		if os.Getenv(key) == "" {
			os.Setenv(key, value)
		}
	}
}

// getEnv retrieves an environment variable with a default fallback value.
func getEnv(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}
