// Package execruntimeenv defines the daemon-owned environment boundary for the
// hidden AgentTeam Exec transport.
package execruntimeenv

import (
	"errors"
	"os"
	"strings"
)

const (
	// BaseURL is the canonical local Exec action endpoint inherited by an
	// authorized runtime.
	BaseURL = "AGENTTEAM_EXEC_BASE_URL"
	// TokenFile is the daemon-owned locator for the current bearer generation.
	TokenFile = "AGENTTEAM_EXEC_TOKEN_FILE"
	// retiredRawToken is scrubbed from inherited environments but never exposed
	// as an accepted credential source.
	retiredRawToken = "AGENTTEAM_EXEC_TOKEN"
	// Retired Extension variables are scrubbed at the unified Exec boundary so
	// an upgraded daemon never propagates a predecessor process capability.
	retiredExtensionBaseURL   = "AGENTTEAM_EXTENSION_BASE_URL"
	retiredExtensionTokenFile = "AGENTTEAM_EXTENSION_TOKEN_FILE"
	retiredExtensionRawToken  = "AGENTTEAM_EXTENSION_TOKEN"
)

// IsDaemonOwnedKey reports whether key names any AgentTeam Exec runtime variable.
// Environment names are compared case-insensitively so mixed-case overrides
// cannot shadow canonical values on Windows.
func IsDaemonOwnedKey(key string) bool {
	switch {
	case strings.EqualFold(strings.TrimSpace(key), BaseURL):
		return true
	case strings.EqualFold(strings.TrimSpace(key), retiredRawToken):
		return true
	case strings.EqualFold(strings.TrimSpace(key), TokenFile):
		return true
	case strings.EqualFold(strings.TrimSpace(key), retiredExtensionBaseURL):
		return true
	case strings.EqualFold(strings.TrimSpace(key), retiredExtensionTokenFile):
		return true
	case strings.EqualFold(strings.TrimSpace(key), retiredExtensionRawToken):
		return true
	default:
		return false
	}
}

// FilterInherited removes AgentTeam Exec variables from an inherited environment.
// Canonical values, when authorized, must be appended by the dispatcher after
// this boundary has been applied.
func FilterInherited(env []string) []string {
	filtered := make([]string, 0, len(env))
	for _, entry := range env {
		key, _, ok := strings.Cut(entry, "=")
		if ok && IsDaemonOwnedKey(key) {
			continue
		}
		filtered = append(filtered, entry)
	}
	return filtered
}

// ClearProcess removes an inherited Exec capability from the current process.
// A nested daemon calls this before starting any helper processes; the daemon
// later authors a distinct capability explicitly for each managed runtime.
func ClearProcess() error {
	var errs []error
	for _, entry := range os.Environ() {
		key, _, ok := strings.Cut(entry, "=")
		if !ok || !IsDaemonOwnedKey(key) {
			continue
		}
		if err := os.Unsetenv(key); err != nil {
			errs = append(errs, err)
		}
	}
	return errors.Join(errs...)
}
