package ecs

import (
	
	
	
)

// storage is the central storage for entities and components.
//
// Also manages the query cache and observers.
type storage struct {
	entities           []entityIndex             // Entity positions in archetypes, indexed by entity ID
	isTarget           []bool                    // Whether each entity is a target of a relationship
	graph              graph                     // Graph for fast archetype traversal
	archetypes         []archetype               // All archetypes
	archetypesData     pagedSlice[archetypeData] // Data for all archetypes
	allArchetypes      []archetypeID             // list of all archetype IDs to simplify usage of componentIndex
	componentIndex     [][]archetypeID           // Archetypes indexed by components IDs; each archetype appears under all its component IDs
	relationArchetypes []archetypeID             // All archetypes with relationships
	tables             []table                   // All tables
	components         []componentStorage        // Component storages for fast random/world access
	cache              cache                     // Filter cache
	entityPool         entityPool                // Entity pool for creation and recycling
	registry           componentRegistry         // Component registry
	locks              lock                      // World locks
	config             config                    // Storage configuration (initial capacities)
	slices             *slices                   // Slices for internal re-use
	observers          *observerManager          // Observer/event manager
}

// componentStorage is an index for faster access of table columns by component ID.
type componentStorage struct {
	columns []*column
}

// slices for re-use, to avoid allocations.
type slices struct {
	batches []batchTable
	tables  []tableID
	ints    []uint32

	relations        []relationID
	relationsCleanup []relationID

	entities        []Entity
	entitiesCleanup []Entity
}

// newSlices creates a new slices.
func newSlices() *slices {
	return &slices{
		batches: make([]batchTable, 0, 32),
		tables:  make([]tableID, 0, 32),
		ints:    make([]uint32, 0, 32),

		relations:        make([]relationID, 0, 8),
		relationsCleanup: make([]relationID, 0, 8),

		entities:        make([]Entity, 0, 16),
		entitiesCleanup: make([]Entity, 0, 256),
	}
}

// newStorage creates a new storage with the given initial number of archetypes
// and the given initial entities capacity.
func newStorage( int,  ...int) storage {
	 := newConfig(...)

	 := newComponentRegistry()
	 := make([]entityIndex, reservedEntities, .initialCapacity+reservedEntities)
	 := make([]bool, reservedEntities, .initialCapacity+reservedEntities)
	// Reserved zero and wildcard entities
	for  := range reservedEntities {
		[] = entityIndex{table: maxTableID, row: 0}
	}
	 := make([]int16, maskTotalBits)
	for  := range maskTotalBits {
		[] = -1
	}

	 := make([]archetype, 0, )
	 := newPagedSlice[archetypeData](32)
	,  := newArchetype(0, 0, &bitMask{}, nil, []tableID{0}, &)
	.Add()
	.archetypeData = .Get(.len - 1)
	 = append(, )

	 := make([]table, 0, )
	 = append(, newTable(0, &[0], uint32(.initialCapacity), &, nil, nil))
	return storage{
		config:         ,
		registry:       ,
		locks:          newLock(),
		observers:      newObserverManager(),
		cache:          newCache(),
		entities:       ,
		isTarget:       ,
		entityPool:     newEntityPool(uint32(.initialCapacity), reservedEntities),
		graph:          newGraph(),
		slices:         newSlices(),
		archetypes:     ,
		archetypesData: ,
		allArchetypes:  []archetypeID{0},
		componentIndex: make([][]archetypeID, 0, maskTotalBits),
		tables:         ,
		components:     make([]componentStorage, 0, maskTotalBits),
	}
}

// findOrCreateTable finds or creates the table resulting from a given table and component additions and removals.
func ( *storage) ( *table,  []ID,  []ID,  []relationID,  *bitMask) (*table, *archetype, bool) {
	 := .archetypes[.archetype].node

	 := .graph.Find(, , , )
	var  *archetype
	if ,  := .GetArchetype();  {
		 = &.archetypes[]
	} else {
		 = .createArchetype()
	}

	 := false
	 := .slices.relations
	 := true
	if len() > 0 {
		// filter out removed relations
		for ,  := range .relationIDs {
			if .mask.Get(.component.id) {
				 = append(, )
			} else {
				 = true
			}
		}
		 = append(, ...)
	} else {
		if len() > 0 {
			 = append(, .relationIDs...)
			 = append(, ...)
		} else {
			 = .relationIDs
			 = false
		}
	}
	,  := .GetTable(, )
	if ! {
		if  {
			// Copy the slice, as it comes from the slice pool
			 := make([]relationID, len())
			copy(, )
			 = .createTable(, )
		} else {
			 = .createTable(, )
		}
	}
	if  {
		.slices.relations = [:0]
	}
	return , , 
}

// findOrCreateTable finds or creates the table resulting from a given table and component additions.
func ( *storage) ( *table,  []ID,  []relationID,  *bitMask,  archetypeID) (*table, *archetype) {
	 := .archetypes[.archetype].node

	var  *archetype
	if  > 0 {
		 = &.archetypes[]
	} else {
		 := .graph.FindAdd(, , )
		if ,  := .GetArchetype();  {
			 = &.archetypes[]
		} else {
			 = .createArchetype()
		}
	}

	 := .slices.relations
	 := true
	if len() > 0 {
		 = append(, .relationIDs...)
		 = append(, ...)
	} else {
		 = .relationIDs
		 = false
	}

	,  := .GetTable(, )
	if ! {
		if  {
			// Copy the slice, as it comes from the slice pool
			 := make([]relationID, len())
			copy(, )
			 = .createTable(, )
		} else {
			 = .createTable(, )
		}
	}
	if  {
		.slices.relations = [:0]
	}
	return , 
}

// findOrCreateTable finds or creates the table resulting from a given table and component removals.
func ( *storage) ( *table,  []ID,  *bitMask) (*table, *archetype, bool) {
	 := .archetypes[.archetype].node

	 := .graph.FindRemove(, , )
	var  *archetype
	if ,  := .GetArchetype();  {
		 = &.archetypes[]
	} else {
		 = .createArchetype()
	}

	 := false
	 := .slices.relations
	for ,  := range .relationIDs {
		if .mask.Get(.component.id) {
			 = append(, )
		} else {
			 = true
		}
	}
	,  := .GetTable(, )
	if ! {
		// Copy the slice, as it comes from the slice pool
		 := make([]relationID, len())
		copy(, )
		 = .createTable(, )
	}
	.slices.relations = [:0]
	return , , 
}

// AddComponent adds a component ID to the storage
func ( *storage) ( uint8) {
	if len(.components) != int() {
		panic("components can only be added to a storage sequentially")
	}
	.components = append(.components, componentStorage{
		columns: make([]*column, len(.tables)),
	})
	.componentIndex = append(.componentIndex, []archetypeID{})
}

// RemoveEntity removes the given entity from the world.
func ( *storage) ( Entity) {
	if !.entityPool.Alive() {
		panic("can't remove a dead entity")
	}
	 := &.entities[.id]
	 := &.tables[.table]

	 := .observers.HasObservers(OnRemoveEntity)
	 := .HasRelations() && .observers.HasObservers(OnRemoveRelations)
	if  ||  {
		 := .lock()
		if  {
			 := &.archetypes[.archetype].mask
			.observers.FireRemoveEntity(, )
		}
		if  {
			 := &.archetypes[.archetype].mask
			.observers.FireRemoveEntityRel(, )
		}
		.unlock()
	}

	 := .Remove(.row)

	.entityPool.Recycle()

	if  {
		 := .GetEntity(uintptr(.row))
		.entities[.id].row = .row
	}
	.table = maxTableID

	if .isTarget[.id] {
		.cleanupArchetypes()
		.isTarget[.id] = false
	}
}

// Reset the storage.
func ( *storage) () {
	.entities = .entities[:reservedEntities]
	.entityPool.Reset()
	.isTarget = .isTarget[:reservedEntities]
	.cache.Reset()
	.locks.Reset()
	.observers.Reset()

	for  := range .archetypes {
		.archetypes[].Reset()
	}
}

// get returns a pointer to the component of given ID for the given entity.
//
// Checks whether the entity is alive.
func ( *storage) ( Entity,  ID) unsafe.Pointer {
	if !.entityPool.Alive() {
		panic("can't get component of a dead entity")
	}
	return .getUnchecked(, )
}

// get returns a pointer to the component of given ID for the given entity.
//
// Does NOT check whether the entity is alive.
func ( *storage) ( Entity,  ID) unsafe.Pointer {
	.checkHasComponent(, )
	 := .entities[.id]
	return .tables[.table].Get(, uintptr(.row))
}

// get returns whether the given entity has the given component.
//
// Checks whether the entity is alive.
func ( *storage) ( Entity,  ID) bool {
	if !.entityPool.Alive() {
		panic("can't check component of a dead entity")
	}
	return .hasUnchecked(, )
}

// get returns whether the given entity has the given component.
//
// Does NOT check whether the entity is alive.
func ( *storage) ( Entity,  ID) bool {
	 := .entities[.id]
	return .tables[.table].Has()
}

// getRelation returns the relation target target of the given entity for the given component.
//
// Checks whether the entity is alive.
// Also checks whether the entity has the component.
// Returns the zero entity if the component is not a relation.
func ( *storage) ( Entity,  ID) Entity {
	if !.entityPool.Alive() {
		panic("can't get relation for a dead entity")
	}
	.checkHasComponent(, )
	return .tables[.entities[.id].table].GetRelation()
}

// getRelationUnchecked returns the relation target target of the given entity for the given component.
//
// Does NOT check whether the entity is alive.
// Also checks whether the entity has the component.
// Returns the zero entity if the component is not a relation.
func ( *storage) ( Entity,  ID) Entity {
	.checkHasComponent(, )
	return .tables[.entities[.id].table].GetRelation()
}

// registerTargets registers the target entities of the given relations
// as relation targets.
//
// Required for cleanup when relation target entities are removed from the world.
func ( *storage) ( []relationID) {
	for ,  := range  {
		.isTarget[.target.id] = true
	}
}

// registerFilter registers a filter and relations.
func ( *storage) ( *filter,  []relationID) {
	.cache.register(, , )
}

// unregisterFilter un-registers a filter.
func ( *storage) ( *filter) {
	.cache.unregister()
}

// getRegisteredFilter returns the cache entry for a cacheID.
func ( *storage) ( cacheID) *cacheEntry {
	return .cache.getEntry()
}

// createEntity creates an entity in the given table.
// Returns the entity and its table row.
func ( *storage) ( tableID) (Entity, uint32) {
	 := .entityPool.Get()
	 := .tables[].Add()
	if int(.id) == len(.entities) {
		.entities = append(.entities, entityIndex{table: , row: })
		.isTarget = append(.isTarget, false)
	} else {
		.entities[.id] = entityIndex{table: , row: }
		.isTarget[.id] = false
	}
	return , 
}

// createEntities creates multiple entities in the given table.
func ( *storage) ( *table,  int) {
	 := .Len()
	.Alloc(uint32())

	 := len(.entities)
	for  := range  {
		 := uint32( + )
		 := .entityPool.Get()
		.SetEntity(, )

		if int(.id) ==  {
			.entities = append(.entities, entityIndex{table: .id, row: })
			.isTarget = append(.isTarget, false)
			++
		} else {
			.entities[.id] = entityIndex{table: .id, row: }
			.isTarget[.id] = false
		}
	}
}

// createArchetype creates an archetype for the given node and adds it to the storage.
func ( *storage) ( *node) *archetype {
	 := .mask.toTypes(&.registry.registry)
	 := len(.archetypes)

	,  := newArchetype(archetypeID(), .id, &.mask, , nil, &.registry)
	.archetypesData.Add()
	.archetypeData = .archetypesData.Get(.archetypesData.len - 1)
	.archetypes = append(.archetypes, )

	 := &.archetypes[]
	.archetype = .id

	.allArchetypes = append(.allArchetypes, .id)
	for ,  := range .components {
		.componentIndex[.id] = append(.componentIndex[.id], .id)
		.registry.addArchetype(.id)
	}
	if .HasRelations() {
		.relationArchetypes = append(.relationArchetypes, .id)
	}

	return 
}

// createTable creates a new table in the given archetype, for the given relations.
// May recycle a free table.
func ( *storage) ( *archetype,  []relationID) *table {
	 := make([]Entity, len(.components))

	if uint8(len()) < .numRelations {
		panic("relation targets must be fully specified")
	}
	for ,  := range  {
		 := .componentsMap[.component.id]
		[] = .target
	}
	for  := range  {
		 := &[]
		.checkRelationComponent(.component)
		.checkRelationTarget(.target)
	}

	var  tableID
	 := false
	if ,  := .GetFreeTable();  {
		 = 
		.tables[].Recycle(, )
		 = true
	} else {
		 = tableID(len(.tables))
		 := .config.initialCapacity
		if .HasRelations() {
			 = .config.initialCapacityRelations
		}
		.tables = append(.tables, newTable(
			, , uint32(), &.registry,
			, ))
	}
	.AddTable(&.tables[])

	 := &.tables[]
	if ! {
		for  := range .components {
			 := ID{id: uint8()}
			 := &.components[]
			if .mask.Get(.id) {
				.columns = append(.columns, .Column())
			} else {
				.columns = append(.columns, nil)
			}
		}
	}

	.cache.addTable(, )
	return 
}

// Removes empty archetypes that have a target relation to the given entity.
func ( *storage) ( Entity) {
	 := .slices.relationsCleanup

	 := .observers.HasObservers(OnAddRelations)
	 := .observers.HasObservers(OnRemoveRelations)
	 :=  || 
	var  bitMask
	var  *bitMask
	var  uint8
	if  {
		 = &
		 = .lock()
	}

	for ,  := range .relationArchetypes {
		 := &.archetypes[]

		,  := .targetTables[.id]
		if ! {
			continue
		}
		 := len(.tables)
		for  :=  - 1;  >= 0; -- {
			 := &.tables[.tables[]]

			for ,  := range .relationIDs {
				// There may be other removed target entities
				if .target.id == .id || !.entityPool.Alive(.target) {
					 = append(, relationID{component: .component, target: Entity{}})
				}
			}

			if .Len() > 0 {
				if  {
					.Reset()
				}
				 := .getExchangeTargetsUnchecked(, , )
				,  := .GetTable(, )
				if ! {
					// Copy the slice, as it comes from the slice pool
					 := make([]relationID, len())
					copy(, )
					 = .createTable(, )
					// Get the old table again, as pointers may have changed.
					 = &.tables[.id]
				}
				.slices.relations = [:0]

				 := .Len()
				 := int(.len)

				if  {
					.observers.FireSetRelationsBatch(OnRemoveRelations, , 0, , &, &.mask)
				}

				.moveEntities(, , uint32(.Len()))

				if  {
					.observers.FireSetRelationsBatch(OnAddRelations, , , +, &, &.mask)
				}
			}
			.FreeTable()
			.cache.removeTable()

			 = [:0]
		}
		.RemoveTarget()
	}
	.slices.relationsCleanup = [:0]

	if  {
		.unlock()
	}
}

// moveEntities moves all entities from src to dst.
func ( *storage) (,  *table,  uint32) {
	 := .Len()
	.AddAll(, )

	 := .Len()
	 := .id
	for  := ;  < ; ++ {
		 := .GetEntity(uintptr())
		.entities[.id] = entityIndex{table: , row: uint32()}
	}
	.Reset()
}

// getExchangeTargetsUnchecked returns the relations resulting from changing relations on a table.
//
// Does not check validity of relations.
//
// The returned slice comes from the pool and should be recycled.
func ( *storage) ( *table,  []relationID,  *bitMask) []relationID {
	 := .slices.entities
	for  := range .columns {
		 = append(, .columns[].target)
	}
	for ,  := range  {
		 := .components[.component.id]
		if .target == [.index] {
			continue
		} else if  != nil {
			.Set(.component.id)
		}
		[.index] = .target
	}

	 := .slices.relations
	for ,  := range  {
		if !.columns[].isRelation {
			continue
		}
		 := .ids[]
		 = append(, relationID{component: , target: })
	}
	.slices.entities = [:0]
	return 
}

// getExchangeTargets returns the relations resulting from changing relations on a table.
//
// Checks validity of relations.
func ( *storage) ( *table,  []relationID,  *bitMask) ([]relationID, bool) {
	 := false
	 := .slices.entities
	for  := range .columns {
		 = append(, .columns[].target)
	}
	for ,  := range  {
		// Validity of the target is checked when creating a new table.
		// Whether the component is a relation is checked when creating a new table.
		 := .components[.component.id]
		if  == nil {
			,  := .registry.ComponentType(.component.id)
			panic(fmt.Sprintf("entity has no component of type %s to set relation target for", .Name()))
		}
		if .target == [.index] {
			continue
		} else if  != nil {
			.Set(.component.id)
		}
		[.index] = .target
		 = true
	}
	if ! {
		return nil, false
	}

	 := make([]relationID, 0, len(.relationIDs))
	for ,  := range  {
		if !.columns[].isRelation {
			continue
		}
		 := .ids[]
		 = append(, relationID{component: , target: })
	}
	.slices.entities = [:0]
	return , true
}

// getBatchTables returns the IDs of all tables that match the given batch.
//
// The returned slice comes from the pool and should be recycled.
func ( *storage) ( *Batch) []tableID {
	 := .slices.tables

	if .filter.cache != maxCacheID {
		 := .getRegisteredFilter(.filter.cache)
		for ,  := range .tables.tables {
			 := &.tables[]
			if .Len() == 0 {
				continue
			}
			if !.Matches(.relations) {
				continue
			}
			 = append(, )
		}
		return 
	}

	for  := range .archetypes {
		 := &.archetypes[]
		if !.filter.matches(&.mask) {
			continue
		}

		if !.HasRelations() {
			 := &.tables[.tables.tables[0]]
			 = append(, .id)
			continue
		}

		 := .GetTables(.relations)
		for ,  := range  {
			 := &.tables[]
			if !.Matches(.relations) {
				continue
			}
			 = append(, )
		}
	}
	return 
}

// getCacheTables returns the IDs of all tables matching the given filter and relations.
func ( *storage) ( *filter,  []relationID) []tableID {
	 := []tableID{}

	for  := range .archetypes {
		 := &.archetypes[]
		if !.matches(&.mask) {
			continue
		}

		if !.HasRelations() {
			 = append(, .tables.tables[0])
			continue
		}

		 := .GetTables()
		for ,  := range  {
			 := &.tables[]
			if !.Matches() {
				continue
			}
			 = append(, )
		}
	}
	return 
}

// Shrink reduces memory usage by shrinking the capacity of archetype tables.
// See [World.Shrink] for details.
func ( *storage) ( time.Duration) bool {
	 := time.Now()
	var  int
	 := false
	for  = range .tables {
		 := &.tables[]

		if !.HasRelations() {
			if .Shrink(uint32(.config.initialCapacity)) {
				 = true
			}
		} else {
			if .Shrink(uint32(.config.initialCapacityRelations)) {
				 = true
			}
			if !.isFree && .Len() == 0 {
				.archetypes[.archetype].FreeTable()
				 = true
			}
		}

		if  && ( == 0 || time.Since() >= ) {
			break
		}
	}

	++
	for  < len(.tables) {
		 := &.tables[]

		if !.HasRelations() {
			if .CanShrink(uint32(.config.initialCapacity)) {
				return true
			}
		} else {
			if .CanShrink(uint32(.config.initialCapacityRelations)) {
				return true
			}
			if !.isFree && .Len() == 0 {
				return true
			}
		}

		++
	}

	return false
}

// lock the world and get the lock bit for later unlocking.
func ( *storage) () uint8 {
	return .locks.Lock()
}

// unlock unlocks the given lock bit.
func ( *storage) ( uint8) {
	.locks.Unlock()
}