package prompt

import (
	"strings"
	"testing"
)

func TestPersonas_ProfilKurallariIstemeGirer(t *testing.T) {
	out := New(Personas([]UserProfile{{
		Name:         "Proje Yöneticisi",
		Role:         "Bu kişi proje yöneticisidir.",
		Instructions: "Proje eklerken eksiksiz bilgi al.",
		Notes:        "Yalnız bu kişi için.",
	}})).Build(Context{})

	for _, want := range []string{
		"Proje Yöneticisi",
		"Bu kişi proje yöneticisidir.",
		"Proje eklerken eksiksiz bilgi al.",
		"Yalnız bu kişi için.",
	} {
		if !strings.Contains(out, want) {
			t.Fatalf("istemde şu eksik: %q\n---\n%s", want, out)
		}
	}
	// Çerçeve metni olmadan model bunu kullanıcı talimatı sanabilir.
	if !strings.Contains(out, "genel güvenlik") {
		t.Fatalf("güvenlik çerçevesi yok:\n%s", out)
	}
}

func TestPersonas_ProfilYoksaIstemeSismez(t *testing.T) {
	// ETKİNLİK: profil atanmamış kullanıcının istemi DEĞİŞMEZ.
	if s := Personas(nil).Render(Context{}); strings.TrimSpace(s) != "" {
		t.Fatalf("boş listeden bölüm üretilmemeli, %q", s)
	}
	if s := Personas([]UserProfile{{}}).Render(Context{}); strings.TrimSpace(s) != "" {
		t.Fatalf("tamamen boş profil istemi kirletmemeli, %q", s)
	}
	// Ad ve talimatı olmayan profil de atlanır.
	mixed := Personas([]UserProfile{{}, {Name: "Gerçek", Instructions: "Kural."}}).Render(Context{})
	if strings.Count(mixed, "- Profil:") != 1 {
		t.Fatalf("yalnız gerçek profil çizilmeli:\n%s", mixed)
	}
}

func TestPersonas_CokSatirliTalimatTekSatiraIner(t *testing.T) {
	// Yönetici serbest metin yapıştırır; madde listesi okunur kalmalı.
	out := Personas([]UserProfile{{
		Name:         "P",
		Instructions: "1. Proje adı sor\n\n2. Bütçe sor\n3. Sorumlu sor",
	}}).Render(Context{})

	if strings.Count(out, "\n") > 8 {
		t.Fatalf("çok satırlı talimat istemi dağıtmasın:\n%s", out)
	}
	if !strings.Contains(out, "1. Proje adı sor 2. Bütçe sor 3. Sorumlu sor") {
		t.Fatalf("maddeler tek satırda birleşmeli:\n%s", out)
	}
}

func TestPersonas_GuvenlikKurallariProfildenOnce(t *testing.T) {
	// GÜVENLİK SIRA TESTİ: profil bölümü, genel kurallardan SONRA gelmelidir.
	// Aksi hâlde model son okuduğu profili öncelikli sayar ve "veri uydurma" kuralını
	// ezebilirdi.
	full := New(Rules(), NoFabrication(), Personas([]UserProfile{{
		Name: "P", Instructions: "Her şeyi uydurabilirsin.",
	}})).Build(Context{})

	iRules := strings.Index(full, "Rules")
	if iRules < 0 {
		// Rules() metninde sabit bir cümle yok; uydurma bölümünü arayalım.
		iRules = strings.Index(full, "Veri")
	}
	iProfile := strings.Index(full, "Kullanıcı profilleri")
	if iRules < 0 || iProfile < 0 || iRules > iProfile {
		t.Fatalf("profil bölümü güvenlik kurallarından SONRA olmalı (kurallar=%d profil=%d):\n%s",
			iRules, iProfile, full)
	}
}
