// Copyright (c) 2024-2026 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.

// control.go
package kern

import "strings"

// Preset control variables
const (
	ControlPreset        = "_preset"
	ControlLastResult    = "last"
	ControlBoolShortcut  = "_bool_shortcut"
	ControlSearchPath    = "_search_path"
	ControlParentContext = "_parent_context"
	ControlStdout        = "_stdout"
)

// Other control variables
const (
	ControlExportAll = "_export_all"
)

// Initial values
const (
	init_search_path = "~/.local/lib/go-pkg/expr:/usr/local/lib/go-pkg/expr:/usr/lib/go-pkg/expr"
)

func CtrlIsEnabled(ctx ExprContext, name string) (status bool) {
	var v any
	var exists bool

	if !strings.HasPrefix(name, "_") {
		name = "_" + name
	}

	if v, exists = ctx.GetVar(name); !exists {
		if globalCtx := ctx.GetGlobal(); globalCtx != nil {
			v, exists = globalCtx.GetVar(name)
		}
	}

	if exists {
		if b, ok := v.(bool); ok {
			status = b
		}
	}
	return
}
func SetCtrl(ctx ExprContext, name string, value any) (current any) {
	current, _ = ctx.GetVar(name)
	ctx.UnsafeSetVar(name, value)
	return
}

func InitDefaultVars(ctx ExprContext) {
	if _, exists := ctx.GetVar(ControlPreset); exists {
		return
	}
	ctx.UnsafeSetVar(ControlPreset, true)
	ctx.UnsafeSetVar(ControlBoolShortcut, true)
	ctx.UnsafeSetVar(ControlSearchPath, init_search_path)
}
