package combatturns

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

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

func TestRegisterPromptAssetsAndPrepareCombatPrompt(t *testing.T) {
	registry := llm.NewAssetRegistry()
	if err := RegisterPromptAssets(registry); err != nil {
		t.Fatalf("RegisterPromptAssets() error = %v", err)
	}
	schemaFS, err := registry.SchemaFS()
	if err != nil {
		t.Fatal(err)
	}
	if _, err := fs.ReadFile(schemaFS, "dnd_combat_turns_llm.v1.json"); err != nil {
		t.Fatalf("response schema asset: %v", err)
	}
	hash, err := promptAssetMetadata()
	if err != nil || !strings.HasPrefix(hash, "sha256:") {
		t.Fatalf("promptAssetMetadata() = %q, %v; want digest", hash, err)
	}
}

func TestPromptAssetsPrepareRequiredInputs(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: "combat-test-profile", Endpoint: "http://127.0.0.1:1/v1", Model: "combat-test-model",
	})))
	engine, err := promptkit.NewEngine(promptkit.Config{Timeout: time.Second}, options...)
	if err != nil {
		t.Fatalf("NewEngine() error = %v, want nil", err)
	}
	transcript := `{"units":[{"sentinel":"combat-transcript"}]}`
	prepared, err := engine.Prepare(context.Background(), promptkit.RunRequest{
		PromptID: PromptID, PromptVersion: SchemaVersion, ProfileID: "combat-test-profile",
		Inputs: map[string]promptkit.ArtifactRef{
			"transcript":   promptkit.InlineWithURI("file:///session.json", transcript),
			"players":      promptkit.Inline("combat-player"),
			"party":        promptkit.Inline(" "),
			"glossary":     promptkit.Inline(" "),
			"npc_registry": promptkit.Inline(`{"npcs":[{"name":"combat-npc"}]}`),
		},
	})
	if err != nil {
		t.Fatalf("Prepare() error = %v, want nil", err)
	}
	if prepared.PromptID != PromptID || prepared.OutputContract.SchemaPath != "dnd_combat_turns_llm.v1.json" {
		t.Fatalf("prepared prompt = %#v, want combat prompt identity and schema", prepared)
	}
}
