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

// operator-digest.go
package expr

import (
	"fmt"
	"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"
)

//-------- digest term

func newDigestTerm(tk *scan.Token) (inst *scan.Term) {
	return &scan.Term{
		Tk:       *tk,
		Children: make([]*scan.Term, 0, 2),
		Position: scan.PosInfix,
		Priority: scan.PriIterOp,
		EvalFunc: evalDigest,
	}
}

func evalDigest(ctx kern.ExprContext, opTerm *scan.Term) (v any, err error) {
	var leftValue, rightValue any
	var it kern.Iterator
	var item, lastValue any

	if err = opTerm.CheckOperands(); err != nil {
		return
	}

	if leftValue, err = opTerm.Children[0].Compute(ctx); err != nil {
		return
	}

	if it, err = NewIterator(ctx, leftValue, nil); err != nil {
		return nil, fmt.Errorf("left operand of DIGEST must be an iterable data-source; got %s", kern.TypeName(leftValue))
	}

	lastValue = nil
	for item, err = it.Next(); err == nil; item, err = it.Next() {
		ctx.SetVar("_", item)
		ctx.SetVar("__", it.Index())
		ctx.SetVar("#", it.Count())
		if rightValue, err = opTerm.Children[1].Compute(ctx); err == nil {
			if rightValue == nil {
				err = io.EOF
			} else {
				lastValue = rightValue
				ctx.SetVar(kern.ControlLastResult, lastValue)
			}
		}
		ctx.DeleteVar("#")
		ctx.DeleteVar("__")
		ctx.DeleteVar("_")
		if err != nil {
			break
		}
	}
	if err == io.EOF {
		err = nil
	}
	v = lastValue
	return
}

// init
func init() {
	scan.RegisterTermConstructor(sym.SymKwDigest, newDigestTerm)
}
