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

// builtins-register.go
package expr

import (
	"fmt"

	"git.portale-stac.it/go-pkg/expr/kern"
)

type builtinModule struct {
	importFunc  func(kern.ExprContext)
	description string
	imported    bool
}

func newBuiltinModule(importFunc func(kern.ExprContext), description string) *builtinModule {
	return &builtinModule{importFunc, description, false}
}

var builtinModuleRegister map[string]*builtinModule

func RegisterBuiltinModule(name string, importFunc func(kern.ExprContext), description string) {
	if builtinModuleRegister == nil {
		builtinModuleRegister = make(map[string]*builtinModule)
	}
	if _, exists := builtinModuleRegister[name]; exists {
		panic(fmt.Errorf("module %q already registered", name))
	}
	builtinModuleRegister[name] = newBuiltinModule(importFunc, description)
}

func IterateBuiltinModules(op func(name, description string, imported bool) bool) {
	if op != nil {
		for name, mod := range builtinModuleRegister {
			if !op(name, mod.description, mod.imported) {
				break
			}
		}
	}
}

// ----
func init() {
	if builtinModuleRegister == nil {
		builtinModuleRegister = make(map[string]*builtinModule)
	}
}
