package ai

import (
	"bytes"
	"context"
	"encoding/json"
	"io"
	"net/http"
	"strings"
	"time"
)

// WebResult is one experiment call (guide: web search vs WikiVectors).
type WebResult struct {
	Answer       string   `json:"answer"`
	Err          string   `json:"err,omitempty"`
	MS           int      `json:"llm_ms"`
	Cost         float64  `json:"cost"`
	PromptTokens int      `json:"prompt_tokens"`
	OutTokens    int      `json:"completion_tokens"`
	URLs         []string `json:"urls,omitempty"`
}

// WebExp calls OpenRouter once. web=true adds the web plugin (Exa, 5 results).
func (s *Store) WebExp(ctx context.Context, model, system, user string, web bool) WebResult {
	var r WebResult
	key, err := s.key(ctx)
	if err != nil {
		r.Err = err.Error()
		return r
	}
	body := map[string]any{
		"model":      model,
		"messages":   []map[string]string{{"role": "system", "content": system}, {"role": "user", "content": user}},
		"max_tokens": 60,
		"usage":      map[string]bool{"include": true},
		"reasoning":  map[string]bool{"enabled": false},
	}
	if web {
		body["plugins"] = []map[string]any{{"id": "web", "engine": "exa", "max_results": 5}}
	}
	b, _ := json.Marshal(body)
	req, _ := http.NewRequestWithContext(ctx, http.MethodPost, "https://openrouter.ai/api/v1/chat/completions", bytes.NewReader(b))
	req.Header.Set("Authorization", "Bearer "+key)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("HTTP-Referer", "https://wikivectors.com")
	req.Header.Set("X-Title", "WikiVectors")
	start := time.Now()
	resp, err := (&http.Client{Timeout: 120 * time.Second}).Do(req)
	r.MS = int(time.Since(start).Milliseconds())
	if err != nil {
		r.Err = err.Error()
		return r
	}
	defer resp.Body.Close()
	raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
	var out struct {
		Choices []struct {
			Message struct {
				Content     string `json:"content"`
				Annotations []struct {
					URLCitation struct {
						URL string `json:"url"`
					} `json:"url_citation"`
				} `json:"annotations"`
			} `json:"message"`
		} `json:"choices"`
		Usage struct {
			Cost             float64 `json:"cost"`
			PromptTokens     int     `json:"prompt_tokens"`
			CompletionTokens int     `json:"completion_tokens"`
		} `json:"usage"`
		Error *struct {
			Message string `json:"message"`
		} `json:"error"`
	}
	json.Unmarshal(raw, &out)
	r.Cost, r.PromptTokens, r.OutTokens = out.Usage.Cost, out.Usage.PromptTokens, out.Usage.CompletionTokens
	if out.Error != nil || len(out.Choices) == 0 {
		r.Err = resp.Status + " " + string(raw[:min(len(raw), 300)])
		return r
	}
	r.Answer = strings.TrimSpace(out.Choices[0].Message.Content)
	for _, a := range out.Choices[0].Message.Annotations {
		if a.URLCitation.URL != "" {
			r.URLs = append(r.URLs, a.URLCitation.URL)
		}
	}
	return r
}
