package npcoccurrences

import (
	"context"
	"io/fs"
	"strings"
	"testing"
	"time"

	"gitea.maximumdirect.net/eric/notarius/internal/framework/llm"
	"gitea.maximumdirect.net/eric/promptkit"
)

func TestRegisterPromptAssetsAndPrepareOccurrencePrompt(t *testing.T) {
	registry := llm.NewAssetRegistry()
	if err := RegisterPromptAssets(registry); err != nil {
		t.Fatal(err)
	}
	schemaFS, err := registry.SchemaFS()
	if err != nil {
		t.Fatal(err)
	}
	if _, err := fs.ReadFile(schemaFS, "dnd_npc_occurrences_llm.v1.json"); err != nil {
		t.Fatalf("response schema asset: %v", err)
	}
	options, err := registry.PromptKitOptions()
	if err != nil {
		t.Fatal(err)
	}
	options = append(options, promptkit.WithProfiles(promptkit.OpenAICompatibleProfile(promptkit.OpenAICompatibleProfileConfig{
		ID: "npc-occurrences-test-profile", Endpoint: "http://127.0.0.1:1/v1", Model: "npc-occurrences-test-model",
	})))
	engine, err := promptkit.NewEngine(promptkit.Config{Timeout: time.Second}, options...)
	if err != nil {
		t.Fatal(err)
	}
	transcript := `{"units":[{"sentinel":"occurrence-transcript"}]}`
	prepared, err := engine.Prepare(context.Background(), promptkit.RunRequest{
		PromptID: PromptID, PromptVersion: SchemaVersion, ProfileID: "npc-occurrences-test-profile",
		Inputs: map[string]promptkit.ArtifactRef{
			"transcript":   promptkit.InlineWithURI("file:///session.json", transcript),
			"players":      promptkit.Inline("occurrence-player"),
			"party":        promptkit.Inline("Mira: ranger"),
			"glossary":     promptkit.Inline("Greencloak: title"),
			"npc_registry": promptkit.Inline(`{"npcs":[{"name":"occurrence-npc"}]}`),
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	if prepared.PromptID != PromptID || prepared.OutputContract.SchemaPath != "dnd_npc_occurrences_llm.v1.json" {
		t.Fatalf("prepared prompt = %#v", prepared)
	}
}

func TestPromptMetadataDoesNotExposeAssetContent(t *testing.T) {
	hash, err := promptAssetMetadata()
	if err != nil || !strings.HasPrefix(hash, "sha256:") {
		t.Fatalf("promptAssetMetadata() = %q, %v", hash, err)
	}
	metadata := newExtractor(t, &fakeOccurrencesLLMClient{}).ManifestMetadata()
	for _, forbidden := range []string{"common-dnd-system", "dnd_npc_occurrences_llm.v1.json"} {
		if strings.Contains(strings.Join(mapValues(metadata), " "), forbidden) {
			t.Fatalf("metadata leaked prompt or schema content %q: %#v", forbidden, metadata)
		}
	}
}

func mapValues(values map[string]any) []string {
	out := make([]string, 0, len(values))
	for _, value := range values {
		if text, ok := value.(string); ok {
			out = append(out, text)
		}
	}
	return out
}
