// Canlı kanıt: kayıtlı profiller GERÇEKTEN ajanın sistem istemine giriyor mu?
// Bu araç, Mongo'daki profilleri okur ve ajanın ürettiği sistem istemini basar.
// (Ajan canlıyken sohbet göndermek yerine istemi doğrudan üretir: test hızlıdır.)
package main

import (
	"context"
	"fmt"
	"os"
	"strings"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"

	"fiko-ai/internal/agent"
	"fiko-ai/internal/persona"
	"fiko-ai/internal/prompt"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()

	uri := os.Getenv("MONGO_URI")
	if uri == "" {
		uri = "mongodb://fikoyt:fikoyt1299@localhost:27017/?authSource=admin"
	}
	db := os.Getenv("MONGO_DATABASE")
	if db == "" {
		db = "fiko_ai"
	}
	cl, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
	if err != nil {
		panic(err)
	}
	defer func() { _ = cl.Disconnect(context.Background()) }()

	// Profilleri doğrudan oku (mongostore'ı kullanmadan; sadece kanıt için).
	cur, err := cl.Database(db).Collection("personas").Find(ctx, bson.M{})
	if err != nil {
		panic(err)
	}
	var profiles []persona.Profile
	if err := cur.All(ctx, &profiles); err != nil {
		panic(err)
	}
	if len(profiles) == 0 {
		fmt.Println("HATA: Mongo'da profil yok; önce panelden bir profil oluştur.")
		os.Exit(1)
	}

	// main.go'daki köprünün AYNI davranışını taklit eden kaynak.
	src := personaSource{profiles: profiles}

	// toolsEnabled=true: profillerin araç kurallarından SONRA geldiğini de görürüz.
	for _, id := range []string{"usr_ee43304df11432ea90af930b", "usr_232de8623cf72e124ca22eba", "tanimsiz-kullanici"} {
		a := &agent.Agent{}
		a.SetPersonas(src)
		sys := a.PreviewSystemPromptFor(context.Background(), id, true)
		var names []string
		for _, p := range a.PersonaProfiles(context.Background(), id) {
			names = append(names, p.Name)
		}
		fmt.Printf("--- kullanıcı %s ---\n", id)
		fmt.Printf("  profiller: %v\n", names)
		if len(names) == 0 {
			fmt.Println("  sistem istemi profil İÇERMEZ (doğru: profili olmayan kullanıcı)")
			continue
		}
		idx := strings.Index(sys, "Kullanıcı profilleri")
		fmt.Printf("  'Kullanıcı profilleri' bölümü var mı: %v\n", idx >= 0)
		// Talimatın İÇERİĞİ gerçekten geçiyor mu? (metin, id değil)
		first := src.profiles[0]
		for _, p := range a.PersonaProfiles(context.Background(), id) {
			if strings.TrimSpace(p.Instructions) != "" {
				first = persona.Profile{Name: p.Name, Instructions: p.Instructions}
			}
		}
		fmt.Printf("  talimatın ilk 40 karakteri istemde: %v\n", strings.Contains(sys, first.Instructions[:40]))
	}
	_ = prompt.Personas
}

// personaSource, agent.PersonaSource arayüzünün canlı veriyle doldurulmuş hâli.
type personaSource struct{ profiles []persona.Profile }

func (p personaSource) ActiveProfiles(_ context.Context, userID string) []agent.Persona {
	var out []agent.Persona
	for _, x := range p.profiles {
		if x.HasUser(userID) {
			out = append(out, agent.Persona{
				Name: x.Name, Role: x.Role, Instructions: x.Instructions, Notes: x.Notes,
			})
		}
	}
	return out
}
