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

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

//-------- include term

func newIncludeTerm(tk *scan.Token) (inst *scan.Term) {
	return &scan.Term{
		Tk:       *tk,
		Children: make([]*scan.Term, 0, 1),
		Position: scan.PosPrefix,
		Priority: scan.PriSign,
		EvalFunc: evalInclude,
	}
}

func evalInclude(ctx kern.ExprContext, opTerm *scan.Term) (v any, err error) {
	var childValue any

	if childValue, err = opTerm.EvalPrefix(ctx); err != nil {
		return
	}

	count := 0
	if array.IsArray(childValue) {
		a, _ := childValue.(*array.ArrayType)
		for i, filePathSpec := range *a {
			if filePath, ok := filePathSpec.(string); ok {
				if v, err = EvalFile(ctx, filePath); err == nil {
					count++
				} else {
					err = opTerm.Errorf("can't load file %q", filePath)
					break
				}
			} else {
				err = opTerm.Errorf("expected string at item nr %d, got %T", i+1, filePathSpec)
				break
			}
		}
	} else if str.IsString(childValue) {
		filePath, _ := childValue.(string)
		if v, err = EvalFile(ctx, filePath); err == nil {
			count++
		}
	} else {
		err = opTerm.ErrIncompatiblePrefixPostfixType(childValue)
	}
	if err != nil {
		//v = count
		v = nil
	}
	return
}

// init
func init() {
	scan.RegisterTermConstructor(sym.SymKwInclude, newIncludeTerm)
}
