package exec

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
	"unicode/utf8"
)

// TestDefaultDescriptorCatalogActionSummaryGolden keeps the persistent prompt
// projection to a domain index plus the common forms that avoid help turns.
func TestDefaultDescriptorCatalogActionSummaryGolden(t *testing.T) {
	catalog, err := DefaultCatalog()
	if err != nil {
		t.Fatal(err)
	}
	got := catalog.RenderActionSummary()
	for _, required := range []string{
		"`agentteam exec --help`",
		"`agentteam exec <domain> --help`",
		"`agentteam exec <domain> <action> --help`",
		"`--input-schema`",
		"`--output-schema`",
	} {
		if !strings.Contains(got, required) {
			t.Fatalf("prompt discovery index missing %q:\n%s", required, got)
		}
	}
	common := make(map[string]bool, len(commonPromptActions))
	for _, ref := range commonPromptActions {
		action, ok := catalog.lookup(ref.domain, ref.name)
		if !ok {
			t.Fatalf("common prompt action %q is not registered", ref.domain+" "+ref.name)
		}
		if len(action.Examples) != 1 {
			t.Fatalf("common prompt action %q has %d examples, want 1", action.identity(), len(action.Examples))
		}
		common[action.identity()] = true
		form := "`agentteam exec " + action.identity() + " '" + compactJSON(action.Examples[0].Input) + "'`"
		if !strings.Contains(got, form) {
			t.Fatalf("prompt common forms missing canonical %q example:\n%s", action.identity(), got)
		}
	}
	for _, action := range catalog.actionsSnapshot() {
		if !strings.Contains(got, "`"+action.Domain+"`") {
			t.Fatalf("prompt discovery index missing domain %q:\n%s", action.Domain, got)
		}
		if !common[action.identity()] && strings.Contains(got, "`agentteam exec "+action.Domain+" "+action.Name+" ") {
			t.Fatalf("prompt must not eagerly list action %q:\n%s", action.identity(), got)
		}
	}
	estimatedTokens := (utf8.RuneCountInString(got) + 3) / 4
	if estimatedTokens < 160 || estimatedTokens > 240 {
		t.Fatalf("prompt estimate = %d tokens, want 160..240:\n%s", estimatedTokens, got)
	}
	goldenPath := filepath.Join("testdata", "action_summary.golden")
	if os.Getenv("UPDATE_GOLDEN") == "1" {
		if err := os.WriteFile(goldenPath, []byte(got), 0o644); err != nil {
			t.Fatal(err)
		}
	}
	want, err := os.ReadFile(goldenPath)
	if err != nil {
		t.Fatal(err)
	}
	if got != string(want) {
		t.Fatalf("action summary differs from golden\n--- got ---\n%s\n--- want ---\n%s", got, want)
	}
}
