package workbench

import (
	"reflect"
	"testing"
)

func TestRenderPromptValidatesRequiredVariables(t *testing.T) {
	definitions := []Variable{{Name: "topic", Required: true}, {Name: "tone", Default: "简洁"}}
	rendered, err := RenderPrompt("用{{ tone }}风格介绍 {{topic}}，保留 {{unknown}}。", definitions, map[string]any{"topic": "Go"})
	if err != nil {
		t.Fatal(err)
	}
	if rendered != "用简洁风格介绍 Go，保留 {{unknown}}。" {
		t.Fatalf("unexpected render: %q", rendered)
	}
	if _, err = RenderPrompt("{{topic}}", definitions, nil); err == nil {
		t.Fatal("expected missing variable error")
	}
}

func TestChunkTextParagraphAwareAndOverlapped(t *testing.T) {
	text := "第一段。\n\n" + repeatRune('甲', 240) + "\n\n最后一段。"
	chunks := ChunkText(text, 200, 20)
	if len(chunks) < 3 {
		t.Fatalf("expected at least 3 chunks, got %d", len(chunks))
	}
	for _, chunk := range chunks {
		if RuneCount(chunk) > 222 {
			t.Fatalf("chunk unexpectedly large: %d", RuneCount(chunk))
		}
	}
}

func TestNormalizeStringsStableDeduplication(t *testing.T) {
	values, err := normalizeStrings([]string{" b ", "a", "b", ""}, 10)
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(values, []string{"b", "a"}) {
		t.Fatalf("unexpected values: %#v", values)
	}
}

func repeatRune(value rune, count int) string {
	runes := make([]rune, count)
	for i := range runes {
		runes[i] = value
	}
	return string(runes)
}
