package message

import (
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"testing"

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

func TestMessageRoutingPlanOwnershipDoesNotDriftToAppPackages(t *testing.T) {
	_, file, _, ok := runtime.Caller(0)
	require.True(t, ok)
	repoRoot := filepath.Clean(filepath.Join(filepath.Dir(file), "..", "..", ".."))

	for _, dir := range []string{
		filepath.Join(repoRoot, "internal", "store", "app"),
		filepath.Join(repoRoot, "internal", "store", "privateagent"),
	} {
		t.Run(filepath.ToSlash(strings.TrimPrefix(dir, repoRoot+string(filepath.Separator))), func(t *testing.T) {
			entries, err := os.ReadDir(dir)
			require.NoError(t, err)
			for _, entry := range entries {
				if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") || strings.HasSuffix(entry.Name(), "_test.go") {
					continue
				}
				path := filepath.Join(dir, entry.Name())
				content, err := os.ReadFile(path)
				require.NoError(t, err)
				for _, line := range strings.Split(string(content), "\n") {
					trimmed := strings.TrimSpace(line)
					if strings.Contains(trimmed, "agentRoutingPlan") ||
						strings.Contains(trimmed, ".durableRecipients") ||
						strings.Contains(trimmed, ".wakeRecipients") ||
						strings.HasPrefix(trimmed, "durableRecipients:") ||
						strings.HasPrefix(trimmed, "wakeRecipients:") {
						rel, relErr := filepath.Rel(repoRoot, path)
						require.NoError(t, relErr)
						t.Fatalf("message routing plan ownership belongs to internal/store/message.AgentRoutingPlan; remove app/privateagent local routing-plan aliases or lower-case routing-plan fields from %s", filepath.ToSlash(rel))
					}
				}
			}
		})
	}
}
