package websearch

import (
	"encoding/json"
	"fmt"
	"strings"
)

func jsonPathValue(v any, path string) (any, bool) {
	path = strings.TrimSpace(path)
	if path == "" {
		return v, v != nil
	}
	cur := v
	for _, part := range strings.Split(path, ".") {
		part = strings.TrimSpace(part)
		if part == "" {
			continue
		}
		switch node := cur.(type) {
		case map[string]any:
			next, ok := node[part]
			if !ok {
				return nil, false
			}
			cur = next
		default:
			return nil, false
		}
	}
	return cur, true
}

func jsonFieldString(item any, field string) string {
	val, ok := jsonPathValue(item, field)
	if !ok || val == nil {
		return ""
	}
	switch v := val.(type) {
	case string:
		return strings.TrimSpace(v)
	default:
		return strings.TrimSpace(fmt.Sprint(v))
	}
}

func decodeJSONBody(body []byte) (any, error) {
	var root any
	if err := json.Unmarshal(body, &root); err != nil {
		return nil, err
	}
	return root, nil
}

func resultsArray(root any, path string) ([]any, bool) {
	val, ok := jsonPathValue(root, path)
	if !ok {
		return nil, false
	}
	items, ok := val.([]any)
	return items, ok
}
