package npcregistry

import (
	"context"
	"encoding/json"
	"strings"
	"testing"
	"time"

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

func TestRegisterPromptAssetsAndPrepareNPCPrompt(t *testing.T) {
	registry := llm.NewAssetRegistry()
	if err := RegisterPromptAssets(registry); err != nil {
		t.Fatalf("RegisterPromptAssets() error = %v, want nil", err)
	}
	options, err := registry.PromptKitOptions()
	if err != nil {
		t.Fatalf("PromptKitOptions() error = %v, want nil", err)
	}
	options = append(options, promptkit.WithProfiles(promptkit.OpenAICompatibleProfile(promptkit.OpenAICompatibleProfileConfig{
		ID: "npc-test-profile", Endpoint: "http://127.0.0.1:1/v1", Model: "npc-test-model",
	})))
	engine, err := promptkit.NewEngine(promptkit.Config{Timeout: time.Second}, options...)
	if err != nil {
		t.Fatalf("NewEngine() error = %v, want nil", err)
	}
	prepared, err := engine.Prepare(context.Background(), promptkit.RunRequest{
		PromptID: PromptID, PromptVersion: SchemaVersion, ProfileID: "npc-test-profile",
		Inputs: map[string]promptkit.ArtifactRef{
			"transcript": promptkit.InlineWithURI("file:///session.json", `{"units":[{"sentinel":"npc-transcript"}]}`),
			"players":    promptkit.Inline("npc-player"),
			"party":      promptkit.Inline(" "),
			"glossary":   promptkit.Inline(" "),
		},
	})
	if err != nil {
		t.Fatalf("Prepare() error = %v, want nil", err)
	}
	if prepared.PromptID != PromptID || prepared.OutputContract.SchemaPath != "dnd_npc_registry_llm.v1.json" {
		t.Fatalf("prepared prompt = %#v, want NPC prompt identity and wiring", prepared)
	}
}

func TestPromptMetadataAndDiagnosticsDoNotContainRawAssets(t *testing.T) {
	hash, err := promptAssetMetadata()
	if err != nil || !strings.HasPrefix(hash, "sha256:") {
		t.Fatalf("promptAssetMetadata() = %q, %v; want hash", hash, err)
	}
	metadata := newExtractor(t, &fakeNPCsLLMClient{}).ManifestMetadata()
	payload, err := json.Marshal(metadata)
	if err != nil {
		t.Fatal(err)
	}
	for _, forbidden := range []string{"common-dnd-system", "dnd_npc_registry_llm.v1.json"} {
		if strings.Contains(string(payload), forbidden) {
			t.Fatalf("metadata leaked raw prompt/schema content %q: %s", forbidden, payload)
		}
	}
}
