package services

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	openai "github.com/sashabaranov/go-openai"
	"wa-assistant/backend/embeddingruntime"
)

func TestEmbeddingGemmaSeparatesQueryAndDocumentAndRejectsInvalidVectors(t *testing.T) {
	var inputs []string
	vector := make([]float32, 768)
	vector[0] = 1
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var req struct {
			Model      string
			Dimensions int
			Input      []string
		}
		if json.NewDecoder(r.Body).Decode(&req) != nil || req.Model != embeddingruntime.Model || req.Dimensions != 768 || len(req.Input) != 1 {
			t.Error("wrong local embedding request")
			w.WriteHeader(400)
			return
		}
		inputs = append(inputs, req.Input[0])
		_ = json.NewEncoder(w).Encode(map[string]any{"data": []any{map[string]any{"embedding": vector, "index": 0}}})
	}))
	defer server.Close()
	embMu.Lock()
	oldClient, oldModel, oldDims, oldEnabled := embClient, embModel, embDims, embEnabled
	cfg := openai.DefaultConfig("fixture-only")
	cfg.BaseURL = server.URL
	embClient, embModel, embDims, embEnabled = openai.NewClientWithConfig(cfg), embeddingruntime.Model, 768, true
	embMu.Unlock()
	t.Cleanup(func() {
		embMu.Lock()
		embClient, embModel, embDims, embEnabled = oldClient, oldModel, oldDims, oldEnabled
		embMu.Unlock()
	})
	for _, document := range []bool{false, true} {
		vec, signature, err := embedForTaskWithSignature(context.Background(), "Jam buka toko", document)
		if err != nil || len(vec) != 768 || signature != embeddingruntime.Signature {
			t.Fatalf("local embedding contract: vector=%d signature=%q err=%v", len(vec), signature, err)
		}
		if embeddingMatchesSignature("openai/text-embedding-3-small:768", signature, vec, vec) {
			t.Fatal("old provider vectors were accepted")
		}
	}
	if inputs[0] != "task: search result | query: Jam buka toko" || inputs[1] != "title: none | text: Jam buka toko" {
		t.Fatal("query/document prefixes were not applied")
	}
	for _, invalid := range [][]float32{{1, 0}, make([]float32, 768)} {
		vector = invalid
		if _, _, err := embedContextWithSignature(context.Background(), "test"); err == nil {
			t.Fatal("invalid vector accepted")
		}
	}
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	if _, _, err := embedContextWithSignature(ctx, "test"); err == nil {
		t.Fatal("canceled embedding request succeeded")
	}
}

func TestEmbeddingGemmaInitializationDoesNotUseCloudSettings(t *testing.T) {
	embMu.Lock()
	oldClient, oldModel, oldDims, oldEnabled := embClient, embModel, embDims, embEnabled
	embMu.Unlock()
	t.Cleanup(func() {
		embMu.Lock()
		embClient, embModel, embDims, embEnabled = oldClient, oldModel, oldDims, oldEnabled
		embMu.Unlock()
	})
	t.Setenv("OPENROUTER_API_KEY", "fixture-unused-key")
	InitEmbedding()
	if EmbeddingEnabled() {
		t.Fatal("embedding reported ready before a model was loaded")
	}
	if !strings.HasPrefix(embSignature(), "embeddinggemma-2:") {
		t.Fatal("local model not selected")
	}
}
