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

// operator-filter.go
package expr

import (
	"fmt"

	"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/boolean"
)

//-------- map term

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

func evalFilter(ctx kern.ExprContext, opTerm *scan.Term) (v any, err error) {
	// var leftValue, rightValue any
	var leftValue any
	var it kern.Iterator
	// var item any
	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 FILTER must be an iterable data-source; got %s", kern.TypeName(leftValue))
		}
	}

	// values := kern.NewListA()
	// 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 success, valid := kern.ToBool(rightValue); valid {
	// 			if success {
	// 				values.AppendItem(item)
	// 			}
	// 		} else {
	// 			err = fmt.Errorf("filter expression must return a boolean or a castable to boolean, got %v [%T]", rightValue, rightValue)
	// 		}
	// 	}
	// 	ctx.DeleteVar("_#")
	// 	ctx.DeleteVar("__")
	// 	ctx.DeleteVar("_")
	// 	if err != nil {
	// 		break
	// 	}
	// }
	// if err == io.EOF {
	// 	err = nil
	// }
	// v = values

	v = newFilerIterator(ctx, it, opTerm.Children[1])
	return
}

const filterIteratorType = "filter"

type filterIterator struct {
	kern.IteratorBase
	ctx   kern.ExprContext
	itSrc kern.Iterator
	expr  *scan.Term
}

func newFilerIterator(ctx kern.ExprContext, itSrc kern.Iterator, filterExpr *scan.Term) (it *filterIterator) {
	it = &filterIterator{
		IteratorBase: kern.IteratorBase{},
		ctx:          ctx,
		itSrc:        itSrc,
		expr:         filterExpr,
	}
	it.IteratorBase.Reset()
	return
}

func (it *filterIterator) TypeName() string {
	return filterIteratorType
}

func (it *filterIterator) String() string {
	return fmt.Sprintf("$(%s %s bool-expr)", it.itSrc, filterIteratorType)
}

func (it *filterIterator) Next() (item any, err error) {
	var attempt, result any

	ctx := it.ctx

	for attempt, err = it.itSrc.Next(); err == nil; attempt, err = it.itSrc.Next() {
		ctx.SetVar("_", attempt)
		ctx.SetVar("__", it.Index())
		ctx.SetVar("#", it.Count())
		result, err = it.expr.Compute(ctx)
		ctx.DeleteVar("#")
		ctx.DeleteVar("__")
		ctx.DeleteVar("_")

		if err == nil {
			if success, valid := boolean.ToBool(result); valid {
				if success {
					item = attempt
					break
				}
			} else {
				err = fmt.Errorf("filter expression must return a boolean or a castable to boolean, got %v [%T]", result, result)
			}
		}
		if err != nil {
			break
		}
	}

	it.SetCurrent(item)
	return
}

// func (it *filterIterator) Reset() (err error) {
// 	err = it.itLeft.Reset()
// 	it.IteratorBase.Reset()
// 	return
// }

func (it *filterIterator) CallOperation(name string, args map[string]any) (v any, err error) {
	switch name {
	case kern.NextName:
		v, err = it.Next()
	// case kern.ResetName:
	// 	err = it.Reset()
	// case kern.CleanName:
	// 	err = it.Clean()
	case kern.IndexName:
		v = it.Index()
	case kern.CurrentName:
		v, err = it.Current()
	case kern.CountName:
		v = it.Count()
	default:
		err = kern.ErrNoOperation(name)
	}
	return
}

// init
func init() {
	scan.RegisterTermConstructor(sym.SymKwFilter, newFilterTerm)
}
