package style8d

import "testing"

func TestNormalizeReferenceTextsFromArray(t *testing.T) {
	texts, err := NormalizeReferenceTexts([]string{"第一段參考文字內容超過二十個字元", "第二段參考文字內容也超過二十個字元"}, "")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(texts) != 2 {
		t.Fatalf("texts=%v", texts)
	}
}

func TestNormalizeReferenceTextsFromRawText(t *testing.T) {
	raw := "第一段參考文字內容超過二十個字元\n還有第二行\n\n---\n\n第二段參考文字內容也超過二十個字元"
	texts, err := NormalizeReferenceTexts(nil, raw)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(texts) != 2 {
		t.Fatalf("texts=%v", texts)
	}
}

func TestBuildUserPromptFromTexts(t *testing.T) {
	got := BuildUserPromptFromTexts("我的舊文", "產品教學帳", TextsToPosts([]string{"這是一段超過二十個字的參考文字樣本內容"}))
	if got == "" {
		t.Fatal("empty prompt")
	}
	if !containsAll(got, "我的舊文", "產品教學帳", "[1]") {
		t.Fatalf("prompt=%q", got)
	}
}

func TestBuildStoredProfileFromTexts(t *testing.T) {
	out, err := ParseLLMOutput(`{"d1Tone":{"summary":"口語","evidence":[]},"d2Structure":{"summary":"短句","evidence":[]},"d3Interaction":{"summary":"提問","evidence":[]},"d4Topics":{"summary":"生活","evidence":[]},"d5Rhythm":{"summary":"晚間","evidence":[]},"d6Visual":{"summary":"emoji","evidence":[]},"d7Conversion":{"summary":"留言","evidence":[]},"d8Risk":{"summary":"硬銷","evidence":[]},"personaDraft":{"identity":"觀察者","tone":"輕鬆","audience":"上班族","hooks":"痛點","examples":"有時候真的會累","avoid":"硬銷"}}`)
	if err != nil {
		t.Fatalf("parse: %v", err)
	}
	profile := BuildStoredProfileFromTexts("手動貼文", TextsToPosts([]string{"sample text long enough"}), out)
	if profile.SourceType != SourceTypeManual {
		t.Fatalf("sourceType=%q", profile.SourceType)
	}
	if profile.Engagement.Verdict != "not_applicable" {
		t.Fatalf("verdict=%q", profile.Engagement.Verdict)
	}
	if ManualStyleBenchmark("手動貼文") != "manual:手動貼文" {
		t.Fatal("manual benchmark mismatch")
	}
}

func containsAll(s string, parts ...string) bool {
	for _, part := range parts {
		if !contains(s, part) {
			return false
		}
	}
	return true
}

func contains(s, sub string) bool {
	return len(sub) == 0 || (len(s) >= len(sub) && indexOf(s, sub) >= 0)
}

func indexOf(s, sub string) int {
	for i := 0; i+len(sub) <= len(s); i++ {
		if s[i:i+len(sub)] == sub {
			return i
		}
	}
	return -1
}
