package ark

import (
	
	

	

	amgraph 
	am 
)

const (
	// PeerPrefix is the prefix of peer machine IDs in the graph.
	PeerPrefix = "peer"
	// TopicTag is the peer tag prefix representing a topic subscription.
	TopicTag = "topic"
)

var peerSchema = am.Schema{"Ready": {}}

// Peer is a pubsub peer entity.
type Peer struct {
	ID string
}

// Topic is a pubsub topic entity.
type Topic struct {
	Name string
}

// Subscription connects a peer to a topic.
type Subscription struct {
	Peer  ecs.Entity
	Topic ecs.Entity
}

// Message is a published topic message.
type Message struct {
	Topic ecs.Entity
	Seq   uint64
	Body  string
}

// Inbox holds message bodies delivered to a peer.
type Inbox struct {
	Messages []string
}

// PubSub is an in-memory pubsub simulation backed by an ark world. Peers and
// topics are entities, subscriptions and messages are entities too. When a
// graph is passed, peer machines are mirrored into it with topic tags.
type PubSub struct {
	world *ecs.World
	graph *amgraph.Graph

	peers  *ecs.Map2[Peer, Inbox]
	inbox  *ecs.Map1[Inbox]
	topics *ecs.Map1[Topic]
	subs   *ecs.Map1[Subscription]
	msgs   *ecs.Map1[Message]

	peerFilter  *ecs.Filter1[Peer]
	topicFilter *ecs.Filter1[Topic]
	subFilter   *ecs.Filter1[Subscription]
	msgFilter   *ecs.Filter1[Message]

	peerIDs  map[string]ecs.Entity
	topicIDs map[string]ecs.Entity
	subIDs   map[subKey]ecs.Entity
	peerTags map[string][]string

	seq        uint64
	deliveries int
}

type subKey struct {
	peer  string
	topic string
}

// NewPubSub creates an in-memory pubsub over world. A nil world creates a new
// one. A nil graph disables graph mirroring.
func ( *ecs.World,  *amgraph.Graph) *PubSub {
	if  == nil {
		 = ecs.NewWorld()
	}
	return &PubSub{
		world:       ,
		graph:       ,
		peers:       ecs.NewMap2[Peer, Inbox](),
		inbox:       ecs.NewMap1[Inbox](),
		topics:      ecs.NewMap1[Topic](),
		subs:        ecs.NewMap1[Subscription](),
		msgs:        ecs.NewMap1[Message](),
		peerFilter:  ecs.NewFilter1[Peer](),
		topicFilter: ecs.NewFilter1[Topic](),
		subFilter:   ecs.NewFilter1[Subscription](),
		msgFilter:   ecs.NewFilter1[Message](),
		peerIDs:     make(map[string]ecs.Entity),
		topicIDs:    make(map[string]ecs.Entity),
		subIDs:      make(map[subKey]ecs.Entity),
		peerTags:    make(map[string][]string),
	}
}

// AddPeer adds a peer by ID. Returns an error if the peer already exists.
func ( *PubSub) ( string) (ecs.Entity, error) {
	if  == "" {
		return ecs.Entity{}, fmt.Errorf("empty peer ID")
	}
	if ,  := .peerIDs[];  {
		return ecs.Entity{}, fmt.Errorf("peer %q already exists", )
	}

	 := .peers.NewEntity(&Peer{ID: }, &Inbox{})
	.peerIDs[] = 
	.updatePeerGraph()
	return , nil
}

// RemovePeer removes a peer, its subscriptions, and its graph machine.
func ( *PubSub) ( string) error {
	,  := .peerIDs[]
	if ! {
		return fmt.Errorf("peer %q not found", )
	}

	for ,  := range .subIDs {
		if .peer !=  {
			continue
		}
		.world.RemoveEntity()
		delete(.subIDs, )
	}
	delete(.peerIDs, )
	delete(.peerTags, )
	.world.RemoveEntity()

	if .graph != nil {
		_ = .graph.RemoveMachine(peerMachineID())
	}
	return nil
}

// AddTopic adds a topic by name. Returns an error if it already exists.
func ( *PubSub) ( string) (ecs.Entity, error) {
	if  == "" {
		return ecs.Entity{}, fmt.Errorf("empty topic name")
	}
	if ,  := .topicIDs[];  {
		return ecs.Entity{}, fmt.Errorf("topic %q already exists", )
	}

	 := .topics.NewEntity(&Topic{Name: })
	.topicIDs[] = 
	return , nil
}

// RemoveTopic removes a topic and all its subscriptions.
func ( *PubSub) ( string) error {
	,  := .topicIDs[]
	if ! {
		return fmt.Errorf("topic %q not found", )
	}

	for ,  := range .subIDs {
		if .topic ==  {
			.world.RemoveEntity()
			delete(.subIDs, )
			.removePeerTag(.peer, )
		}
	}
	delete(.topicIDs, )
	.world.RemoveEntity()
	return nil
}

// Subscribe subscribes a peer to a topic. Re-subscribing is a no-op.
func ( *PubSub) (,  string) error {
	,  := .peerIDs[]
	if ! {
		return fmt.Errorf("peer %q not found", )
	}
	,  := .topicIDs[]
	if ! {
		return fmt.Errorf("topic %q not found", )
	}

	 := subKey{peer: , topic: }
	if ,  := .subIDs[];  {
		return nil
	}
	.subIDs[] = .subs.NewEntity(&Subscription{Peer: , Topic: })
	.addPeerTag(, )
	return nil
}

// Unsubscribe removes a peer's subscription. Missing subscriptions are a
// no-op.
func ( *PubSub) (,  string) {
	 := subKey{peer: , topic: }
	,  := .subIDs[]
	if ! {
		return
	}
	.world.RemoveEntity()
	delete(.subIDs, )
	.removePeerTag(, )
}

// Publish publishes a message to a topic and delivers it to all current
// subscribers. It returns the number of deliveries.
func ( *PubSub) (,  string) (int, error) {
	,  := .topicIDs[]
	if ! {
		return 0, fmt.Errorf("topic %q not found", )
	}

	.seq++
	.msgs.NewEntity(&Message{Topic: , Seq: .seq, Body: })

	 := 0
	 := .subFilter.Query()
	for .Next() {
		 := .Get()
		if .Topic !=  {
			continue
		}
		 := .inbox.Get(.Peer)
		.Messages = append(.Messages, )
		++
	}
	.Close()
	.deliveries += 
	return , nil
}

// Inbox returns a copy of a peer's delivered messages.
func ( *PubSub) ( string) ([]string, error) {
	,  := .peerIDs[]
	if ! {
		return nil, fmt.Errorf("peer %q not found", )
	}
	return slices.Clone(.inbox.Get().Messages), nil
}

// Tags returns a copy of a peer's topic tags.
func ( *PubSub) ( string) []string {
	return slices.Clone(.peerTags[])
}

// PeerCount returns the number of peers.
func ( *PubSub) () int {
	return countEntities(.peerFilter)
}

// TopicCount returns the number of topics.
func ( *PubSub) () int {
	return countEntities(.topicFilter)
}

// SubscriptionCount returns the number of subscriptions.
func ( *PubSub) () int {
	return countEntities(.subFilter)
}

// MessageCount returns the number of published messages.
func ( *PubSub) () int {
	return countEntities(.msgFilter)
}

// DeliveryCount returns the total number of deliveries.
func ( *PubSub) () int {
	return .deliveries
}

func countEntities[ any]( *ecs.Filter1[]) int {
	 := .Query()
	 := .Count()
	.Close()
	return 
}

// addPeerTag adds a topic tag and mirrors the peer into the graph.
func ( *PubSub) (,  string) {
	 := TopicTag + ":" + 
	if slices.Contains(.peerTags[], ) {
		return
	}
	.peerTags[] = append(.peerTags[], )
	.updatePeerGraph()
}

// removePeerTag removes a topic tag and mirrors the peer into the graph.
func ( *PubSub) (,  string) {
	 := TopicTag + ":" + 
	 := .peerTags[]
	if  := slices.Index(, );  >= 0 {
		.peerTags[] = slices.Delete(, , +1)
	}
	.updatePeerGraph()
}

// updatePeerGraph mirrors a peer into the graph as a machine with topic tags.
func ( *PubSub) ( string) {
	if .graph == nil {
		return
	}
	_ = .graph.AddMachine(&amgraph.Machine{
		Serialized: &am.Serialized{
			ID:         peerMachineID(),
			StateNames: am.S{"Ready"},
			Time:       am.Time{1},
			Tags:       slices.Clone(.peerTags[]),
		},
		Schema:     peerSchema,
		SchemaHash: "ark-peer",
		MTimeSum:   1,
	})
}

func peerMachineID( string) string {
	return PeerPrefix + "-" + 
}