package graph

import (
	
	
	
	

	

	amtypes 
	am 
)

var (
	ErrVertexNotFound = errors.New("vertex not found")
	ErrEdgeNotFound   = errors.New("edge not found")
	ErrPathNotFound   = errors.New("path not found")
)

// Edge is a directed graph edge between two vertex hashes.
type Edge struct {
	Source     string
	Target     string
	Properties EdgeProperties
}

// EdgeProperties contains edge metadata.
type EdgeProperties struct {
	Data any
}

func ( Edge) () *EdgeData {
	,  := .Properties.Data.(*EdgeData)
	return 
}

type edgeKey struct {
	source string
	target string
}

// edgeBase is the required component of an edge entity.
type edgeBase struct {
	source string
	target string
}

// Typed edge metadata components. Each GQL relationship label is a separate
// optional component, so edges can be queried by kind using ark ECS filters.

type (
	// edgeMachHas is the (Machine)-[:HAS]->(State) metadata.
	edgeMachHas struct{ MachineHas }
	// edgeMachHasTag is the (Machine)-[:HAS_TAG]->(Tag) metadata.
	edgeMachHasTag struct{}
	// edgeMachChildOf is the (Machine)-[:CHILD_OF]->(Machine) metadata.
	edgeMachChildOf struct{}
	// edgeMachConnectedTo is the (Machine)-[:CONNECTED_TO]->(Machine) metadata.
	edgeMachConnectedTo struct{}
	// edgeMachPipe is the (Machine)-[:PIPE]->(Machine) metadata. Each pipe is
	// a separate edge entity.
	edgeMachPipe struct{ MachPipeTo }

	// TODO perf: make these optional (dont index)

	// edgeStateRequire is the (State)-[:REQUIRE]->(State) metadata.
	edgeStateRequire struct{}
	// edgeStateAdd is the (State)-[:ADD]->(State) metadata.
	edgeStateAdd struct{}
	// edgeStateRemove is the (State)-[:REMOVE]->(State) metadata.
	edgeStateRemove struct{}
	// edgeStateAfter is the (State)-[:AFTER]->(State) metadata.
	edgeStateAfter struct{}
)

// edgeComp is a typed ark ECS map and filter of one optional edge component,
// bound to the owning store for projections.
type edgeComp[ any] struct {
	s *store
	m *ecs.Map1[]
	f *ecs.Filter1[]
}

func newEdgeComp[ any]( *store) edgeComp[] {
	return edgeComp[]{
		s: ,
		m: ecs.NewMap1[](.world),
		f: ecs.NewFilter1[](.world),
	}
}

func ( edgeComp[]) ( ecs.Entity) * {
	return .m.Get()
}

func ( edgeComp[]) ( ecs.Entity) bool {
	return .m.HasAll()
}

// set upserts the component, or removes it for a nil value. The caller must
// hold the lock.
func ( edgeComp[]) ( ecs.Entity,  *) {
	if  == nil {
		.clear()
		return
	}
	if  := .m.Get();  != nil {
		* = *
		return
	}
	.m.Add(, )
}

// clear removes the component. The caller must hold the lock.
func ( edgeComp[]) ( ecs.Entity) {
	if .m.HasAll() {
		.m.Remove()
	}
}

// edges returns all graph edges having the component, optionally filtered by
// source.
func ( edgeComp[]) ( string) []Edge {
	var  []Edge
	 := .f.Query()
	for .Next() {
		 := .Entity()
		 := .s.em.Get()
		if  != "" && .source !=  {
			continue
		}
		 := edgeKey{source: .source, target: .target}
		 = append(, .s.edgeValue(, ))
	}
	.Close()

	return 
}

// store is an ark ECS-backed graph store. Vertices and edges are entities with
// typed components, indexed by their string hash.
type store struct {
	mu sync.RWMutex

	world *ecs.World
	verts map[string]ecs.Entity
	edges map[edgeKey]ecs.Entity
	// pipes indexes pipe entities by their machine pair.
	pipes map[edgeKey][]ecs.Entity

	vm *ecs.Map1[Vertex]
	vf *ecs.Filter1[Vertex]
	em *ecs.Map1[edgeBase]

	// Typed edge metadata, one component per GQL relationship label.

	has     edgeComp[edgeMachHas]
	hasTag  edgeComp[edgeMachHasTag]
	childOf edgeComp[edgeMachChildOf]
	connTo  edgeComp[edgeMachConnectedTo]
	pipe    edgeComp[edgeMachPipe]
	require edgeComp[edgeStateRequire]
	add     edgeComp[edgeStateAdd]
	remove  edgeComp[edgeStateRemove]
	after   edgeComp[edgeStateAfter]
}

func newStore( *ecs.World) *store {
	if  == nil {
		 = ecs.NewWorld()
	}
	 := &store{
		world: ,
		verts: make(map[string]ecs.Entity),
		edges: make(map[edgeKey]ecs.Entity),
		pipes: make(map[edgeKey][]ecs.Entity),
		vm:    ecs.NewMap1[Vertex](),
		vf:    ecs.NewFilter1[Vertex](),
		em:    ecs.NewMap1[edgeBase](),
	}
	.has = newEdgeComp[edgeMachHas]()
	.hasTag = newEdgeComp[edgeMachHasTag]()
	.childOf = newEdgeComp[edgeMachChildOf]()
	.connTo = newEdgeComp[edgeMachConnectedTo]()
	.pipe = newEdgeComp[edgeMachPipe]()
	.require = newEdgeComp[edgeStateRequire]()
	.add = newEdgeComp[edgeStateAdd]()
	.remove = newEdgeComp[edgeStateRemove]()
	.after = newEdgeComp[edgeStateAfter]()

	return 
}

// ///// ///// /////

// ///// VERTICES

// ///// ///// /////

func ( *store) ( *Vertex) error {
	.mu.Lock()
	defer .mu.Unlock()

	.addVertexUnlocked()
	return nil
}

// addVertexUnlocked upserts a vertex. The caller must hold the lock.
func ( *store) ( *Vertex) bool {
	 := hash()
	if ,  := .verts[];  {
		return false
	}
	.verts[] = .vm.NewEntity()
	return true
}

func ( *store) ( string) (*Vertex, error) {
	.mu.RLock()
	defer .mu.RUnlock()

	return .vertexUnlocked()
}

func ( *store) ( string) (*Vertex, error) {
	,  := .verts[]
	if ! {
		return nil, fmt.Errorf("%w: %q", ErrVertexNotFound, )
	}
	 := *.vm.Get()
	return &, nil
}

func ( *store) () []*Vertex {
	.mu.RLock()
	defer .mu.RUnlock()

	return .verticesUnlocked()
}

func ( *store) () []*Vertex {
	 := make([]*Vertex, 0, len(.verts))
	 := .vf.Query()
	for .Next() {
		 := *.Get()
		 = append(, &)
	}
	.Close()
	return 
}

// Snapshot returns all vertices and edges in one batch.
func ( *store) () ([]*Vertex, []Edge) {
	.mu.RLock()
	defer .mu.RUnlock()

	return .verticesUnlocked(), .edgesUnlocked()
}

// removeVertices removes vertices and all their inbound and outbound edges.
func ( *store) ( map[string]struct{}) {
	.mu.Lock()
	defer .mu.Unlock()

	for ,  := range .edges {
		if ,  := [.source];  {
			.world.RemoveEntity()
			delete(.edges, )
			.removePipesUnlocked()
			continue
		}
		if ,  := [.target];  {
			.world.RemoveEntity()
			delete(.edges, )
			.removePipesUnlocked()
		}
	}
	for  := range  {
		if ,  := .verts[];  {
			.world.RemoveEntity()
			delete(.verts, )
		}
	}
}

// reset removes all graph entities, keeping the world and its custom entities.
func ( *store) () {
	.mu.Lock()
	defer .mu.Unlock()

	for ,  := range .edges {
		.world.RemoveEntity()
		.removePipesUnlocked()
	}
	clear(.edges)
	for ,  := range .verts {
		.world.RemoveEntity()
		delete(.verts, )
	}
}

// removeIncidentEdges removes all inbound and outbound edges of a vertex.
func ( *store) ( string) {
	.mu.Lock()
	defer .mu.Unlock()

	for ,  := range .edges {
		if .source ==  || .target ==  {
			.world.RemoveEntity()
			delete(.edges, )
			.removePipesUnlocked()
		}
	}
}

// ///// ///// /////

// ///// EDGES

// ///// ///// /////

func ( *store) (,  string,  *EdgeData) error {
	.mu.Lock()
	defer .mu.Unlock()

	return .addEdgeUnlocked(, , )
}

func ( *store) (,  string,  *EdgeData) error {
	if ,  := .verts[]; ! {
		return fmt.Errorf("%w: %q", ErrVertexNotFound, )
	}
	if ,  := .verts[]; ! {
		return fmt.Errorf("%w: %q", ErrVertexNotFound, )
	}

	 := edgeKey{source: , target: }
	,  := .edges[]
	if ! {
		 = .em.NewEntity(&edgeBase{source: , target: })
		.edges[] = 
	}
	.mergeEdgeData(, , )

	return nil
}

// UpdateEdge replaces all metadata of an edge.
func ( *store) (,  string,  *EdgeData) error {
	.mu.Lock()
	defer .mu.Unlock()

	 := edgeKey{source: , target: }
	,  := .edges[]
	if ! {
		return fmt.Errorf("%w: %q -> %q", ErrEdgeNotFound, , )
	}
	.clearEdgeData()
	.removePipesUnlocked()
	.mergeEdgeData(, , )

	return nil
}

func ( *store) (,  string) error {
	.mu.Lock()
	defer .mu.Unlock()

	 := edgeKey{source: , target: }
	,  := .edges[]
	if ! {
		return nil
	}
	.world.RemoveEntity()
	delete(.edges, )
	.removePipesUnlocked()
	return nil
}

func ( *store) (,  string) (Edge, error) {
	.mu.RLock()
	defer .mu.RUnlock()

	return .edgeUnlocked(, )
}

func ( *store) (,  string) (Edge, error) {
	 := edgeKey{source: , target: }
	,  := .edges[]
	if ! {
		return Edge{}, fmt.Errorf("%w: %q -> %q", ErrEdgeNotFound, , )
	}
	return .edgeValue(, ), nil
}

func ( *store) () []Edge {
	.mu.RLock()
	defer .mu.RUnlock()

	return .edgesUnlocked()
}

func ( *store) () []Edge {
	 := make([]Edge, 0, len(.edges))
	for ,  := range .edges {
		 = append(, .edgeValue(, ))
	}
	return 
}

// edgeValue projects an edge entity and its typed components into the public
// [Edge] type.
func ( *store) ( edgeKey,  ecs.Entity) Edge {
	return Edge{
		Source:     .source,
		Target:     .target,
		Properties: EdgeProperties{Data: .edgeData(, )},
	}
}

// edgesOfKind returns all edges of a GQL relationship label, optionally
// filtered by source. Pipes are returned one edge per pipe.
func ( *store) ( amtypes.RelKind,  string) []Edge {
	.mu.RLock()
	defer .mu.RUnlock()

	switch  {
	case amtypes.RelHas:
		return .has.edges()
	case amtypes.RelHasTag:
		return .hasTag.edges()
	case amtypes.RelChildOf:
		return .childOf.edges()
	case amtypes.RelConnectedTo:
		return .connTo.edges()
	case amtypes.RelPipe:
		return .pipeEdgesUnlocked()
	case amtypes.RelRequire:
		return .require.edges()
	case amtypes.RelAdd:
		return .add.edges()
	case amtypes.RelRemove:
		return .remove.edges()
	case amtypes.RelAfter:
		return .after.edges()
	}

	return nil
}

// pipeEdgesUnlocked returns one edge per pipe. The caller must hold the lock.
func ( *store) ( string) []Edge {
	var  []Edge
	 := .pipe.f.Query()
	for .Next() {
		 := .Entity()
		 := .em.Get()
		if  != "" && .source !=  {
			continue
		}
		 := .Get().MachPipeTo
		 = append(, Edge{
			Source: .source,
			Target: .target,
			Properties: EdgeProperties{Data: &EdgeData{
				MachPipesTo: []*MachPipeTo{&},
			}},
		})
	}
	.Close()

	return 
}

func ( *store) () map[string]map[string]Edge {
	.mu.RLock()
	defer .mu.RUnlock()

	 := make(map[string]map[string]Edge, len(.verts))
	for  := range .verts {
		[] = make(map[string]Edge)
	}
	for ,  := range .edges {
		if ,  := [.source];  {
			[.target] = .edgeValue(, )
		}
	}
	return 
}

func ( *store) () map[string]map[string]Edge {
	.mu.RLock()
	defer .mu.RUnlock()

	 := make(map[string]map[string]Edge, len(.verts))
	for  := range .verts {
		[] = make(map[string]Edge)
	}
	for ,  := range .edges {
		if ,  := [.target];  {
			[.source] = .edgeValue(, )
		}
	}
	return 
}

// shortestPath performs an undirected BFS between two vertices.
func ( *store) (,  string) ([]string, error) {
	.mu.RLock()
	defer .mu.RUnlock()

	if ,  := .verts[]; ! {
		return nil, fmt.Errorf("%w: %q", ErrVertexNotFound, )
	}
	if ,  := .verts[]; ! {
		return nil, fmt.Errorf("%w: %q", ErrVertexNotFound, )
	}

	 := make(map[string][]string, len(.verts))
	for  := range .edges {
		[.source] = append([.source], .target)
		[.target] = append([.target], .source)
	}

	 := map[string]string{: ""}
	 := []string{}
	for len() > 0 {
		 := [0]
		 = [1:]
		if  ==  {
			break
		}
		for ,  := range [] {
			if ,  := [];  {
				continue
			}
			[] = 
			 = append(, )
		}
	}

	if ,  := []; ! {
		return nil, fmt.Errorf("%w: %q -> %q", ErrPathNotFound, , )
	}
	 := []string{}
	for  := ;  != ; {
		 = []
		 = append(, )
	}
	slices.Reverse()
	return , nil
}

// ///// ///// /////

// ///// BATCH

// ///// ///// /////

// addBatch creates missing vertices and edges in batches. Existing edges are
// merged with the new metadata.
func ( *store) ( []*Vertex,  []Edge) error {
	.mu.Lock()
	defer .mu.Unlock()

	// vertices
	 := make([]*Vertex, 0, len())
	 := make(map[string]struct{}, len())
	for ,  := range  {
		if  == nil {
			continue
		}
		 := hash()
		if ,  := .verts[];  {
			continue
		}
		if ,  := [];  {
			continue
		}
		[] = struct{}{}
		 = append(, )
	}
	// validate edge endpoints before creating anything
	for ,  := range  {
		if ,  := [.Source]; ! {
			if ,  := .verts[.Source]; ! {
				return fmt.Errorf("%w: %q", ErrVertexNotFound, .Source)
			}
		}
		if ,  := [.Target]; ! {
			if ,  := .verts[.Target]; ! {
				return fmt.Errorf("%w: %q", ErrVertexNotFound, .Target)
			}
		}
	}

	if len() > 0 {
		 := 0
		.vm.NewBatchFn(len(), func( ecs.Entity,  *Vertex) {
			* = *[]
			.verts[hash([])] = 
			++
		})
	}

	// edges
	for ,  := range  {
		 := edgeKey{source: .Source, target: .Target}
		,  := .edges[]
		if ! {
			 = .em.NewEntity(&edgeBase{source: .source, target: .target})
			.edges[] = 
		}
		.mergeEdgeData(, , .data())
	}

	return nil
}

func ( *store) () *store {
	.mu.RLock()
	 := .verticesUnlocked()
	 := .edgesUnlocked()
	.mu.RUnlock()

	 := newStore(nil)
	_ = .addBatch(, )
	return 
}

// ///// ///// /////

// ///// EDGE DATA

// ///// ///// /////

// mergeEdgeData applies metadata to an edge entity, preserving the existing
// metadata. The caller must hold the lock.
func ( *store) ( ecs.Entity,  edgeKey,  *EdgeData) {
	if  == nil {
		return
	}
	if .MachHas != nil {
		.has.set(, &edgeMachHas{*.MachHas})
	}
	if .MachConnectedTo {
		.connTo.set(, &edgeMachConnectedTo{})
	}
	if .MachChildOf {
		.childOf.set(, &edgeMachChildOf{})
	}
	if .MachHasTag {
		.hasTag.set(, &edgeMachHasTag{})
	}
	for ,  := range .MachPipesTo {
		if  != nil {
			.addPipeUnlocked(, )
		}
	}
	for ,  := range .StateRelation {
		if  == nil {
			continue
		}
		switch .RelType {
		case am.RelationRequire:
			.require.set(, &edgeStateRequire{})
		case am.RelationAdd:
			.add.set(, &edgeStateAdd{})
		case am.RelationRemove:
			.remove.set(, &edgeStateRemove{})
		case am.RelationAfter:
			.after.set(, &edgeStateAfter{})
		}
	}
}

// clearEdgeData removes all metadata components of an edge entity. The caller
// must hold the lock.
func ( *store) ( ecs.Entity) {
	.has.clear()
	.connTo.clear()
	.childOf.clear()
	.hasTag.clear()
	.require.clear()
	.add.clear()
	.remove.clear()
	.after.clear()
}

// edgeData projects the typed components of an edge entity into [EdgeData].
func ( *store) ( ecs.Entity,  edgeKey) *EdgeData {
	 := &EdgeData{}

	if  := .has.get();  != nil {
		.MachHas = &MachineHas{Auto: .Auto, Multi: .Multi}
	}
	if .connTo.has() {
		.MachConnectedTo = true
	}
	if .childOf.has() {
		.MachChildOf = true
	}
	if .hasTag.has() {
		.MachHasTag = true
	}
	for ,  := range .pipes[] {
		if  := .pipe.get();  != nil {
			 := .MachPipeTo
			.MachPipesTo = append(.MachPipesTo, &)
		}
	}
	if .require.has() {
		.StateRelation = append(.StateRelation,
			&StateRelation{RelType: am.RelationRequire})
	}
	if .add.has() {
		.StateRelation = append(.StateRelation,
			&StateRelation{RelType: am.RelationAdd})
	}
	if .remove.has() {
		.StateRelation = append(.StateRelation,
			&StateRelation{RelType: am.RelationRemove})
	}
	if .after.has() {
		.StateRelation = append(.StateRelation,
			&StateRelation{RelType: am.RelationAfter})
	}

	return 
}

// addPipeUnlocked upserts a pipe entity for a machine pair. The caller must
// hold the lock.
func ( *store) ( edgeKey,  *MachPipeTo) {
	for ,  := range .pipes[] {
		if  := .pipe.get();  != nil &&
			.FromState == .FromState && .ToState == .ToState &&
			.MutType == .MutType {
			return
		}
	}
	 := .em.NewEntity(&edgeBase{source: .source, target: .target})
	.pipe.set(, &edgeMachPipe{MachPipeTo: *})
	.pipes[] = append(.pipes[], )
}

// removePipesUnlocked removes all pipe entities of a machine pair. The caller
// must hold the lock.
func ( *store) ( edgeKey) {
	for ,  := range .pipes[] {
		.world.RemoveEntity()
	}
	delete(.pipes, )
}