package services

import (
	"context"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync/atomic"
	"testing"
	"time"

	"go.opentelemetry.io/otel"
)

func TestLangfuseOTLPExportUsesAuthenticationAndNoSecretPayload(t *testing.T) {
	var requests atomic.Int32
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		requests.Add(1)
		if r.URL.Path != "/api/public/otel/v1/traces" {
			t.Errorf("OTLP path: %s", r.URL.Path)
		}
		u, p, ok := r.BasicAuth()
		if !ok || u != "fixture-public" || p != "fixture-secret" {
			t.Error("OTLP authentication missing")
		}
		if r.Header.Get("x-langfuse-ingestion-version") != "4" {
			t.Error("Langfuse ingestion version missing")
		}
		payload, _ := io.ReadAll(r.Body)
		if strings.Contains(string(payload), "fixture-secret") {
			t.Error("secret leaked to trace payload")
		}
		w.Header().Set("Content-Type", "application/x-protobuf")
		w.WriteHeader(200)
	}))
	defer server.Close()
	t.Setenv("AI_TELEMETRY_ENABLED", "true")
	t.Setenv("LANGFUSE_BASE_URL", server.URL)
	t.Setenv("LANGFUSE_PUBLIC_KEY", "fixture-public")
	t.Setenv("LANGFUSE_SECRET_KEY", "fixture-secret")
	old := otel.GetTracerProvider()
	t.Cleanup(func() { otel.SetTracerProvider(old) })
	shutdown, err := InitAITelemetry(context.Background())
	if err != nil {
		t.Fatal(err)
	}
	ctx := context.WithValue(context.Background(), aiTraceScopeKey{}, aiTraceScope{agentID: 1, dryRun: true})
	_, span := startAISpan(ctx, "fixture.turn", "agent")
	span.End()
	timeout, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	if err := shutdown(timeout); err != nil {
		t.Fatal(err)
	}
	if requests.Load() != 1 {
		t.Fatalf("exports=%d", requests.Load())
	}
}

func TestTelemetryDisabledNeedsNoKeys(t *testing.T) {
	t.Setenv("AI_TELEMETRY_ENABLED", "")
	t.Setenv("LANGFUSE_SECRET_KEY", "")
	shutdown, err := InitAITelemetry(context.Background())
	if err != nil {
		t.Fatal(err)
	}
	if err := shutdown(context.Background()); err != nil {
		t.Fatal(err)
	}
}
