package bootstrap

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

// LoadInfraEnv reads local env files into process env (only keys not already set).
// Search order: HAIXUN_ENV_FILE, deploy/.env.dev (for native dev run).
func LoadInfraEnv() {
	if path := strings.TrimSpace(os.Getenv("HAIXUN_ENV_FILE")); path != "" {
		_ = loadEnvFile(path)
		return
	}
	cwd, err := os.Getwd()
	if err != nil {
		return
	}
	candidates := []string{
		filepath.Join(cwd, "deploy", ".env.dev"),
		filepath.Join(cwd, "..", "deploy", ".env.dev"),
		filepath.Join(cwd, "..", "..", "deploy", ".env.dev"),
	}
	for _, path := range candidates {
		if loadEnvFile(path) {
			return
		}
	}
}

func loadEnvFile(path string) bool {
	f, err := os.Open(path)
	if err != nil {
		return false
	}
	defer f.Close()

	scanner := bufio.NewScanner(f)
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		key, value, ok := strings.Cut(line, "=")
		if !ok {
			continue
		}
		key = strings.TrimSpace(key)
		if key == "" {
			continue
		}
		if _, exists := os.LookupEnv(key); exists {
			continue
		}
		value = strings.TrimSpace(value)
		if len(value) >= 2 {
			if (value[0] == '"' && value[len(value)-1] == '"') ||
				(value[0] == '\'' && value[len(value)-1] == '\'') {
				value = value[1 : len(value)-1]
			}
		}
		_ = os.Setenv(key, value)
	}
	return true
}
