package memory

import (
	"context"
	"fmt"
	"strings"

	"github.com/tidbcloud/AgentTeam/internal/store/content"
)

// ContentAuthorityReader resolves the exact persisted owner for one Memory
// binding without creating default authority rows.
type ContentAuthorityReader interface {
	GetAuthority(context.Context, string, string, string) (content.Authority, bool, error)
	ListAuthoritiesForBindings(context.Context, string, string, []string) (map[string]content.Authority, error)
}

// nativeMemoryRead selects one remote owner for an exact managed-Memory
// binding. Missing authority remains dormant legacy; an activated native
// binding never falls back to AGS when its adapter is unavailable.
func (s *MemoryService) nativeMemoryRead(ctx context.Context, workspaceID, memoryID string) (bool, error) {
	if s == nil || s.contentAuthority == nil {
		return false, nil
	}
	authority, found, err := s.contentAuthority.GetAuthority(ctx, strings.TrimSpace(workspaceID), memoryContentDomain, strings.TrimSpace(memoryID))
	if err != nil {
		return false, fmt.Errorf("resolve memory content authority: %w", err)
	}
	state := content.AuthorityStateLegacyActive
	if found {
		state = strings.TrimSpace(authority.State)
	}
	switch state {
	case content.AuthorityStateLegacyActive:
		return false, nil
	case content.AuthorityStateNativeActive:
		if !s.nativeContentEnabled || s.nativeContent == nil {
			return false, fmt.Errorf("native memory content is unavailable")
		}
		return true, nil
	default:
		return false, fmt.Errorf("unknown memory content authority state %q", state)
	}
}
