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

// operator-insert.go
package expr

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

//-------- prepend term

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

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

func evalPrepend(ctx kern.ExprContext, opTerm *scan.Term) (v any, err error) {
	var leftValue, rightValue any

	if leftValue, rightValue, err = opTerm.EvalInfix(ctx); err != nil {
		return
	}

	if kern.IsList(rightValue) {
		list, _ := rightValue.(*kern.ListType)
		newList := append(kern.ListType{leftValue}, *list...)
		v = &newList
		if opTerm.Children[1].Symbol() == scan.SymVariable {
			ctx.UnsafeSetVar(opTerm.Children[1].Source(), v)
		}
	} else {
		err = opTerm.ErrIncompatibleTypes(leftValue, rightValue)
	}
	return
}

func evalAppend(ctx kern.ExprContext, opTerm *scan.Term) (v any, err error) {
	var leftValue, rightValue any

	if leftValue, rightValue, err = opTerm.EvalInfix(ctx); err != nil {
		return
	}

	if kern.IsList(leftValue) {
		list, _ := leftValue.(*kern.ListType)
		newList := append(*list, rightValue)
		v = &newList
		if opTerm.Children[0].Symbol() == scan.SymVariable {
			ctx.UnsafeSetVar(opTerm.Children[0].Source(), v)
		}
	} else {
		err = opTerm.ErrIncompatibleTypes(leftValue, rightValue)
	}
	return
}

// func evalAssignAppend(ctx ExprContext, self *term) (v any, err error) {
// 	var leftValue, rightValue any

// 	if leftValue, rightValue, err = self.evalInfix(ctx); err != nil {
// 		return
// 	}

// 	if IsList(leftValue) {
// 		list, _ := leftValue.(*ListType)
// 		newList := append(*list, rightValue)
// 		v = &newList
// 		if
// 	} else {
// 		err = self.errIncompatibleTypes(leftValue, rightValue)
// 	}
// 	return
// }

// init
func init() {
	scan.RegisterTermConstructor(scan.SymPlusGreater, newPrependTerm)
	scan.RegisterTermConstructor(scan.SymLessPlus, newAppendTerm)
}
