package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/mwbidwell/wikivectors/internal/ai"
)

const sysNone = "Answer the question in as few words as possible. If you are not sure, answer: I don't know."
const sysCtx = "Answer the question in as few words as possible, using only the context. The context may use different words than the question, and it does not have to repeat every detail of the question. If the context supports an answer, give it. Only if nothing in the context answers the question, answer: I don't know."

func wv(q string) (string, int, error) {
	b, _ := json.Marshal(map[string]any{"query": q, "limit": 5})
	req, _ := http.NewRequest("POST", "https://wikivectors.com/v1/search", bytes.NewReader(b))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("WIKIVECTORS_KEY"))
	req.Header.Set("Content-Type", "application/json")
	t := time.Now()
	resp, err := http.DefaultClient.Do(req)
	ms := int(time.Since(t).Milliseconds())
	if err != nil {
		return "", ms, err
	}
	defer resp.Body.Close()
	var out struct {
		Results []struct{ Title, Section, Text string } `json:"results"`
	}
	json.NewDecoder(resp.Body).Decode(&out)
	var parts []string
	for _, p := range out.Results {
		sec := p.Section
		if sec == "" {
			sec = "intro"
		}
		parts = append(parts, fmt.Sprintf("Page: %s (%s)\n%s", p.Title, sec, p.Text))
	}
	return strings.Join(parts, "\n\n"), ms, nil
}

func main() {
	ctx := context.Background()
	pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
	if err != nil {
		panic(err)
	}
	st := &ai.Store{Pool: pool, Secret: []byte(os.Getenv("SESSION_SECRET"))}
	model := os.Getenv("MODEL")
	var qs []struct{ ID, Question string }
	b, _ := os.ReadFile("/work/ws-questions.json")
	json.Unmarshal(b, &qs)
	var out []map[string]any
	for _, q := range qs {
		user := "Question: " + q.Question
		a := st.WebExp(ctx, model, sysNone, user, false)
		out = append(out, map[string]any{"id": q.ID, "arm": "alone", "r": a})
		w := st.WebExp(ctx, model, sysCtx, user, true)
		out = append(out, map[string]any{"id": q.ID, "arm": "web", "r": w})
		c, sms, err := wv(q.Question)
		v := ai.WebResult{Err: fmt.Sprint(err)}
		if err == nil {
			v = st.WebExp(ctx, model, sysCtx, "Context:\n"+c+"\n\nQuestion: "+q.Question, false)
		}
		out = append(out, map[string]any{"id": q.ID, "arm": "wikivectors", "r": v, "search_ms": sms, "context": c})
		fmt.Fprintln(os.Stderr, q.ID, a.Cost, w.Cost, w.PromptTokens, v.PromptTokens, w.Err, v.Err)
		b, _ = json.MarshalIndent(out, "", " ")
		os.WriteFile("/work/"+os.Getenv("OUT"), b, 0o644)
	}
}
