package maputils

import (
	"errors"
	"strconv"
	"strings"
)

const (
	pathSeparator = "."
)

func FindValueInMap(find map[string]any, path string) (any, error) {
	if find == nil || strings.TrimSpace(path) == "" {
		return nil, errors.New("没有传递需要查找的数据或路径")
	}

	var retValue any
	var currentFind any

	currentFind = find
	pathParts := strings.Split(path, pathSeparator)
	for _, pathPart := range pathParts {
		if strings.HasPrefix(pathPart, "[") && strings.HasSuffix(pathPart, "]") {
			indexStr := strings.TrimLeft(strings.TrimRight(pathPart, "]"), "[")

			index, err := strconv.Atoi(strings.Trim(indexStr, " "))
			if err != nil {
				return nil, err
			}

			findSlice, ok := currentFind.([]any)
			if ok {
				if index > len(findSlice)-1 {
					retValue = nil
				} else {
					retValue = findSlice[index]
				}
			} else {
				findMapSlice, ok := currentFind.([]map[string]any)
				if !ok {
					return nil, errors.New("对应slice路径的值不是slice: " + pathPart)
				}

				if index > len(findMapSlice)-1 {
					retValue = nil
				} else {
					retValue = findMapSlice[index]
				}
			}
		} else {
			findMap, ok := currentFind.(map[string]any)
			if !ok {
				return nil, errors.New("对应map路径的值不是map: " + pathPart)
			}

			value, ok := findMap[pathPart]
			if !ok {
				return nil, nil
			}

			retValue = value
		}

		if retValue == nil {
			return nil, nil
		}

		currentFind = retValue
	}

	return retValue, nil
}