package websearch

import (
	"context"
	"fmt"
	"net/http"
	"strings"
	"time"
)

var braveSearchURL = "https://api.search.brave.com/res/v1/web/search"
var bingSearchURL = "https://api.bing.microsoft.com/v7.0/search"
var duckDuckGoHTMLURL = "https://html.duckduckgo.com/html/"

type Result struct {
	Title       string `json:"title"`
	URL         string `json:"url"`
	Description string `json:"description"`
}

type Client struct {
	http *http.Client
}

func NewClient() *Client {
	return &Client{http: &http.Client{Timeout: 15 * time.Second}}
}

func (c *Client) Search(ctx context.Context, provider Provider, query string, count int) ([]Result, error) {
	query = strings.TrimSpace(query)
	if query == "" {
		return nil, fmt.Errorf("search query is required")
	}
	if count <= 0 {
		count = 5
	}
	if count > 20 {
		count = 20
	}

	switch provider.Type {
	case ProviderBrave:
		return c.searchBrave(ctx, provider.APIKey, query, count)
	case ProviderBing:
		return c.searchBing(ctx, provider, query, count)
	case ProviderDuckDuckGo:
		return c.searchDuckDuckGo(ctx, provider, query, count)
	case ProviderSearXNG:
		return c.searchSearXNG(ctx, provider, query, count)
	case ProviderCustom:
		return c.searchCustom(ctx, provider, query, count)
	default:
		return nil, fmt.Errorf("unsupported search provider type: %s", provider.Type)
	}
}
