package projectmemory

import (
	"strings"
	"testing"

	"github.com/google/uuid"
	"github.com/stretchr/testify/require"
)

func TestRenderAgentsMD_GroupsByKindDeterministic(t *testing.T) {
	entries := []Entry{
		{ID: uuid.New(), Kind: KindGotcha, Title: "Zebra gotcha", Body: "watch out"},
		{ID: uuid.New(), Kind: KindDecision, Title: "Use Postgres", Body: "ACID matters", Tags: []string{"db", "arch"}},
		{ID: uuid.New(), Kind: KindDecision, Title: "Adopt Chi router", Body: "lightweight"},
		{ID: uuid.New(), Kind: KindConvention, Title: "Tabs not spaces", Body: "gofmt"},
	}
	out := renderAgentsMD(entries, nil)

	// Sections appear in canonical kind order: Decisions, Conventions, Gotchas.
	di := strings.Index(out, "## Decisions")
	ci := strings.Index(out, "## Conventions")
	gi := strings.Index(out, "## Gotchas")
	require.Greater(t, di, 0)
	require.Greater(t, ci, di)
	require.Greater(t, gi, ci)

	// Within Decisions, titles are sorted: "Adopt Chi router" before "Use Postgres".
	require.Less(t, strings.Index(out, "Adopt Chi router"), strings.Index(out, "Use Postgres"))

	// Tags are rendered sorted.
	require.Contains(t, out, "Tags: arch, db")

	// Generated banner present.
	require.True(t, strings.HasPrefix(out, agentsMDHeader))

	// Determinism: same input → identical output.
	require.Equal(t, out, renderAgentsMD(entries, nil))
}

func TestRenderAgentsMD_WorkspaceScoping(t *testing.T) {
	ws := uuid.New()
	other := uuid.New()
	entries := []Entry{
		{ID: uuid.New(), Kind: KindDecision, Title: "Project-wide", Body: "x"},                  // ws nil → always
		{ID: uuid.New(), Kind: KindDecision, Title: "WS-specific", Body: "y", WorkspaceID: &ws}, // matches ws
		{ID: uuid.New(), Kind: KindDecision, Title: "Other-WS", Body: "z", WorkspaceID: &other}, // excluded
	}
	out := renderAgentsMD(entries, &ws)
	require.Contains(t, out, "Project-wide")
	require.Contains(t, out, "WS-specific")
	require.NotContains(t, out, "Other-WS")

	// With no workspace, only project-wide entries appear.
	outNil := renderAgentsMD(entries, nil)
	require.Contains(t, outNil, "Project-wide")
	require.NotContains(t, outNil, "WS-specific")
}

func TestRenderAgentsMD_Empty(t *testing.T) {
	out := renderAgentsMD(nil, nil)
	require.Contains(t, out, "No project memory recorded yet")
}
