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

// operator-groupby.go
package expr

import (
	"fmt"
	"io"
	"strconv"

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

//-------- group by term

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

func evalGroupBy(ctx kern.ExprContext, opTerm *scan.Term) (v any, err error) {
	var leftValue, rightValue any
	var it kern.Iterator
	var item any
	var sKey string
	var keyByIndex bool
	var ok bool

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

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

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

	rightTk := opTerm.Children[1].Tk
	if rightTk.IsSymbol(sym.SymVariable) && rightTk.Source() == "__" {
		keyByIndex = true
	} else if rightValue, err = opTerm.Children[1].Compute(ctx); err != nil {
		return
	} else if str.IsString(rightValue) {
		sKey = rightValue.(string)
	} else {
		return nil, fmt.Errorf("right operand of GROUPBY must be a string or identifier '__'; got %s", kern.TypeName(rightValue))
	}

	values := dict.MakeDict()
	for item, err = it.Next(); err == nil; item, err = it.Next() {
		ctx.SetVar("_", item)
		ctx.SetVar("__", it.Index())
		ctx.SetVar("#", it.Count())

		var sItemKey string

		if d, ok := item.(*dict.DictType); ok {
			if keyByIndex || len(sKey) == 0 {
				sItemKey = strconv.Itoa(int(it.Index()))
			} else if d.HasKey(sKey) {
				if keyValue, exists := d.GetItem(sKey); exists {
					if s, ok := keyValue.(string); ok {
						sItemKey = s
					} else {
						sItemKey = fmt.Sprintf("%v", keyValue)
					}
				} else {
					sItemKey = "_"
				}
			} else {
				sItemKey = "_"
			}
		} else {
			sItemKey = strconv.Itoa(int(it.Index()))
		}

		var ls *array.ArrayType
		if lsAny, exists := values.GetItem(sItemKey); exists && lsAny != nil {
			ls = lsAny.(*array.ArrayType)
		}
		if ls == nil {
			ls = array.NewArrayA()
		}
		ls.AppendItem(item)
		values.SetItem(sItemKey, ls)

		ctx.DeleteVar("#")
		ctx.DeleteVar("__")
		ctx.DeleteVar("_")
	}
	if err == io.EOF {
		err = nil
	}
	v = values
	return
}

// init
func init() {
	scan.RegisterTermConstructor(sym.SymKwGroupBy, newGroupByTerm)
}
