package main

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestReadTelegramConfig(t *testing.T) {
	path := filepath.Join(t.TempDir(), "telegram-config")
	if err := os.WriteFile(path, []byte("bot_token=123:abc\nrelay_key=relay-secret\n"), 0600); err != nil {
		t.Fatal(err)
	}
	config, err := readTelegramConfig(path)
	if err != nil {
		t.Fatal(err)
	}
	if config.BotToken != "123:abc" || config.RelayKey != "relay-secret" {
		t.Fatalf("unexpected config: %#v", config)
	}
}

func TestAskTenantUsesAuthenticatedNamedConversation(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		if request.URL.Path != "/v1/responses" {
			t.Fatalf("unexpected path %s", request.URL.Path)
		}
		if request.Header.Get("Authorization") != "Bearer relay-secret" {
			t.Fatal("relay authentication was not set")
		}
		if request.Header.Get("X-Hermes-Session-Key") != "telegram" {
			t.Fatal("Telegram session scope was not set")
		}
		var payload map[string]any
		if err := json.NewDecoder(request.Body).Decode(&payload); err != nil {
			t.Fatal(err)
		}
		if payload["conversation"] != "telegram" || payload["input"] != "hello" {
			t.Fatalf("unexpected payload: %#v", payload)
		}
		writer.Header().Set("Content-Type", "application/json")
		_, _ = writer.Write([]byte(`{"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Hello from Hermes"}]}]}`))
	}))
	defer server.Close()
	router, err := newTenantRouter(filepath.Join(t.TempDir(), "state.json"), 1, func(slot int) string { return "" })
	if err != nil {
		t.Fatal(err)
	}
	router.backendAPIURL = func(slot int) string { return server.URL }
	bot := newTelegramBot(telegramConfig{RelayKey: "relay-secret"}, router)
	answer, err := bot.askTenant(0, "hello", 42)
	if err != nil {
		t.Fatal(err)
	}
	if answer != "Hello from Hermes" {
		t.Fatalf("unexpected answer %q", answer)
	}
}

func TestSplitTelegramTextStaysUnderTelegramLimit(t *testing.T) {
	chunks := splitTelegramText(strings.Repeat("word ", 2000))
	if len(chunks) < 2 {
		t.Fatal("expected a long response to be split")
	}
	for _, chunk := range chunks {
		if len([]rune(chunk)) > 3900 {
			t.Fatalf("chunk exceeds limit: %d", len([]rune(chunk)))
		}
	}
}
