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

// operand-dict.go
package expr

import (
	"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"
	"git.portale-stac.it/go-pkg/expr/types/dict"
	"git.portale-stac.it/go-pkg/expr/types/str"
)

// -------- dict term
func newDictTerm(args map[any]*scan.Term) *scan.Term {
	return &scan.Term{
		Tk:       *scan.NewValueToken(0, 0, sym.SymDict, "{}", args),
		Parent:   nil,
		Children: nil,
		Position: scan.PosLeaf,
		Priority: scan.PriValue,
		EvalFunc: evalDict,
	}
}

// -------- dict func
func evalDict(ctx kern.ExprContext, opTerm *scan.Term) (v any, err error) {
	dt, _ := opTerm.Value().(map[any]*scan.Term)
	items := make(dict.DictType, len(dt))
	for key, tree := range dt {
		var param any
		if param, err = tree.Compute(ctx); err != nil {
			break
		}
		var keyValue any
		if keyValue, err = (key.(*scan.Term)).Compute(ctx); err == nil {
			if types.IsInteger(keyValue) || str.IsString(keyValue) {
				items[keyValue] = param
			} else {
				err = key.(*scan.Term).Errorf("dict key can be integer or string, got %s", kern.TypeName(keyValue))
			}
		}
	}
	if err == nil {
		v = &items
	}
	return
}
