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

// operator-builtin.go
package expr

import (
	"io"

	"git.portale-stac.it/go-pkg/expr/kern"
	"git.portale-stac.it/go-pkg/expr/scan"
	"git.portale-stac.it/go-pkg/expr/sym"
	"git.portale-stac.it/go-pkg/expr/types/str"
)

//-------- builtin term

func newBuiltinTerm(tk *scan.Token) (inst *scan.Term) {
	return &scan.Term{
		Tk:       *tk,
		Children: make([]*scan.Term, 0, 1),
		Position: scan.PosPrefix,
		Priority: scan.PriSign,
		EvalFunc: evalBuiltin,
	}
}

func evalBuiltin(ctx kern.ExprContext, opTerm *scan.Term) (v any, err error) {
	var childValue any

	if childValue, err = opTerm.EvalPrefix(ctx); err != nil {
		return
	}

	count := 0
	if str.IsString(childValue) {
		module, _ := childValue.(string)
		count, err = ImportInContextByGlobPattern(ctx, module)
	} else {
		var moduleSpec any
		var it kern.Iterator
		if it, err = NewIterator(ctx, childValue, nil); err != nil {
			return
		}
		for moduleSpec, err = it.Next(); err == nil; moduleSpec, err = it.Next() {
			if module, ok := moduleSpec.(string); ok {
				if ImportInContext(ctx, module) {
					count++
				} else {
					err = opTerm.Errorf("unknown builtin module %q", module)
					break
				}
			} else {
				err = opTerm.Errorf("expected string at item nr %d, got %s", it.Index()+1, kern.TypeName(moduleSpec))
				break
			}
		}
		if err == io.EOF {
			err = nil
		}
	}
	if err == nil {
		v = int64(count)
	}
	return
}

// init
func init() {
	scan.RegisterTermConstructor(sym.SymKwBuiltin, newBuiltinTerm)
}
