package ecs

import 

type cacheID uint32

const maxCacheID = math.MaxUint32

// Cache entry for a filter.
type cacheEntry struct {
	filter    *filter      // The underlying filter.
	tables    tableIDs     // Tables matching the filter.
	relations []relationID // Entity relationships.
	id        cacheID      // Entry ID.
}

// cache provides filter caching to speed up queries.
//
// For registered filters, the relevant archetypes are tracked internally,
// so that there are no mask checks required during iteration.
// This is particularly helpful to avoid query iteration slowdown by a very high number of archetypes.
// If the number of archetypes exceeds approx. 50-100, uncached filters experience a slowdown.
// The relative slowdown increases with lower numbers of entities queried (noticeable below a few thousand entities).
// Cached filters avoid this slowdown.
//
// The overhead of tracking cached filters internally is very low,
// as updates are required only when new archetypes are created.
type cache struct {
	indices map[cacheID]int  // Mapping from filter IDs to indices in filters
	filters []cacheEntry     // The cached filters, indexed by indices
	intPool intPool[cacheID] // Pool for filter IDs
}

// newCache creates a new [cache].
func newCache() cache {
	return cache{
		intPool: newIntPool[cacheID](128),
		indices: map[cacheID]int{},
		filters: []cacheEntry{},
	}
}

// getEntry returns the cache entry for the given ID.
func ( *cache) ( cacheID) *cacheEntry {
	return &.filters[.indices[]]
}

// register a filter.
func ( *cache) ( *storage,  *filter,  []relationID) {
	// TODO: prevent duplicate registration
	 := .intPool.Get()
	.cache = 
	 := len(.filters)
	 := newTableIDs(.getCacheTables(, )...)
	.filters = append(.filters,
		cacheEntry{
			id:        ,
			filter:    ,
			relations: ,
			tables:    ,
		})
	.indices[] = 
}

// unregister a filter.
func ( *cache) ( *filter) {
	,  := .indices[.cache]
	if ! {
		panic("no filter for id found to unregister")
	}
	delete(.indices, .cache)

	.cache = maxCacheID

	 := len(.filters) - 1
	if  !=  {
		.filters[], .filters[] = .filters[], .filters[]
		.indices[.filters[].id] = 
	}
	.filters[] = cacheEntry{}
	.filters = .filters[:]
}

// addTable adds a table.
//
// Iterates over all filters and adds the node to the resp. entry where the filter matches.
func ( *cache) ( *storage,  *table) {
	 := &.archetypes[.archetype]
	if !.HasRelations() {
		for  := range .filters {
			 := &.filters[]
			if !.filter.matches(&.mask) {
				continue
			}
			.tables.Append(.id)
		}
		return
	}

	for  := range .filters {
		 := &.filters[]
		if !.filter.matches(&.mask) {
			continue
		}
		if !.Matches(.relations) {
			continue
		}
		.tables.Append(.id)
	}
}

// removeTable removes a table.
//
// Can only be used for tables that have a relation target.
// Tables without a relation are never removed.
func ( *cache) ( *table) {
	//if !table.HasRelations() {
	//	// unreachable
	//	return
	//}
	for  := range .filters {
		 := &.filters[]
		.tables.Remove(.id)
	}
}

// Reset the cache.
// Un-registers all filters.
func ( *cache) () {
	if len(.indices) == 0 {
		return
	}
	for  := range .filters {
		 := &.filters[]
		.filter.cache = maxCacheID
	}
	.indices = map[cacheID]int{}
	.filters = .filters[:0]
	.intPool.Reset()
}