package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"time"
)

// QwantAPIResponse represents the JSON response structure from Qwant API
type QwantAPIResponse struct {
	Data struct {
		Result struct {
			Items []struct {
				Media     string `json:"media"`
				Thumbnail string `json:"thumbnail"`
				Title     string `json:"title"`
				Url       string `json:"url"`
				Width     int    `json:"width"`
				Height    int    `json:"height"`
			} `json:"items"`
		} `json:"result"`
	} `json:"data"`
}

// PerformQwantImageSearch performs an image search on Qwant and returns the results.
func PerformQwantImageSearch(query, safe, lang string, page int) ([]ImageSearchResult, time.Duration, error) {
	startTime := time.Now() // Start the timer

	const resultsPerPage = 50
	var offset int
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * resultsPerPage
	}

	if safe == "" {
		safe = "0"
	}

	if lang == "" {
		lang = "en_CA"
	}

	apiURL := fmt.Sprintf("https://api.qwant.com/v3/search/images?t=images&q=%s&count=%d&locale=%s&offset=%d&device=desktop&tgp=2&safesearch=%s",
		url.QueryEscape(query),
		resultsPerPage,
		lang,
		offset,
		safe)

	client := &http.Client{Timeout: 10 * time.Second}

	req, err := http.NewRequest("GET", apiURL, nil)
	if err != nil {
		return nil, 0, fmt.Errorf("creating request: %v", err)
	}

	ImageUserAgent, err := GetUserAgent("Image-Search")
	if err != nil {
		return nil, 0, err
	}

	req.Header.Set("User-Agent", ImageUserAgent)

	resp, err := client.Do(req)
	if err != nil {
		return nil, 0, fmt.Errorf("making request: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, 0, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
	}

	var apiResp QwantAPIResponse
	if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil {
		return nil, 0, fmt.Errorf("decoding response: %v", err)
	}

	var results []ImageSearchResult
	for _, item := range apiResp.Data.Result.Items {
		results = append(results, ImageSearchResult{
			Thumbnail:  item.Thumbnail,
			Title:      item.Title,
			Media:      item.Media,
			Source:     item.Url,
			ThumbProxy: "/img_proxy?url=" + url.QueryEscape(item.Media),
			Width:      item.Width,
			Height:     item.Height,
		})
	}

	duration := time.Since(startTime) // Calculate the duration

	return results, duration, nil
}