package test

import (
	
	
	
	
	
	
	
	
	
	

	

	ssrel 
	amgraph 
	amtypes 
	amhelp 
	am 
	arpc 
	ssrpc 
	ssdbg 
)

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

// ///// MACHINE GRAPH

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

// MachinesPerNode is the number of source machines per graph node.
const MachinesPerNode = 4

// NetworkGraphPushInterval is the graph sync interval used by the simulation.
const NetworkGraphPushInterval = 10 * time.Millisecond

// MachineIds returns the machine IDs owned by a graph node.
func ( string) []string {
	return machineIds(, MachinesPerNode)
}

// machineIds returns count machine IDs owned by a graph node.
func machineIds( string,  int) []string {
	 := make([]string, 0, )
	for  := 1;  <= ; ++ {
		 = append(, fmt.Sprintf("%s-mach-%d", , ))
	}
	return 
}

const DefaultGraphSpec = `
sink

node-1
node-2
node-3
node-4

node-1-1
node-1-2
node-1-3
node-1-4

node-2-1
node-2-2
node-2-3
node-2-4

node-3-1
node-3-2
node-3-3
node-3-4

node-4-1
node-4-2
node-4-3
node-4-4
`

// Node is a parsed Graph node.
type Node struct {
	ID       string
	Parent   string
	Children []string
}

// Graph is a parsed Graph specification.
type Graph struct {
	Root     string
	Nodes    []Node
	ByID     map[string]*Node
	Children map[string][]string
}

func parseSpec( *testing.T,  string) Graph {
	.Helper()

	var  []string
	 := make(map[string]struct{})
	for ,  := range strings.Split(, "\n") {
		 = strings.TrimSpace()
		if  == "" {
			continue
		}
		if ,  := [];  {
			.Fatalf("duplicate node ID %s", )
		}
		[] = struct{}{}
		 = append(, )
	}
	if len() < 2 {
		.Fatalf("Graph spec needs at least a root and one node")
	}

	 := Graph{
		Root:     [0],
		ByID:     make(map[string]*Node),
		Children: make(map[string][]string),
	}
	.ByID[.Root] = &Node{ID: .Root}

	for ,  := range [1:] {
		 := .Root
		if  := strings.LastIndex(, "-");  > 0 {
			 := [:]
			if ,  := [];  {
				 = 
			}
		}
		.Nodes = append(.Nodes, Node{ID: , Parent: })
		.ByID[] = &.Nodes[len(.Nodes)-1]
		.Children[] = append(.Children[], )
	}

	return 
}

// TreeSpec returns a deterministic tree spec with the given depth and fanout.
// The root is "sink"; children are IDs like "node-1", "node-1-2", which
// [parseSpec] links by trimming the last "-" segment.
func (,  int) string {
	var  strings.Builder
	.WriteString("sink\n")

	 := []string{"node"}
	for range  {
		 := make([]string, 0, len()*)
		for ,  := range  {
			for  := 1;  <= ; ++ {
				 := fmt.Sprintf("%s-%d", , )
				.WriteString( + "\n")
				 = append(, )
			}
		}
		 = 
	}

	return .String()
}

// NetNode is one NetworkGraph node with locally traced machines.
type NetNode struct {
	ID       string
	ParentID string
	Machines []*am.Machine
	Server   *am.Machine
	Graph    *amgraph.Graph
	Net      *amgraph.NetworkGraph

	// discovered maps source machine IDs already dialed by this node.
	discovered map[string]struct{}
}

// MachineGraph is a reusable multi-node NetworkGraph test fixture.
type MachineGraph struct {
	T             *testing.T
	Nodes         []*NetNode
	ByID          map[string]*NetNode
	Sink          *NetNode
	Parents       []string
	Children      map[string][]*NetNode
	RelayExpected map[string][]*am.Machine
	NodeMachines  map[string][]*am.Machine
	Machines      []*am.Machine
	Idx           int
	waitTimeout   time.Duration

	ctx              context.Context
	Servers          map[string]*arpc.Server
	Clients          []*arpc.Client
	discoverySources map[string][]string
	discoveryWant    int
	discoveryMx      sync.Mutex
	discoveryWg      sync.WaitGroup
}

// DiscoveryOpts configures [MachineGraph.StartDiscovery].
type DiscoveryOpts struct {
	// SinkOnly runs discovery only on the sink, dialing every source machine
	// visible to it.
	SinkOnly bool
}

// GraphOpts configures [NewMachineGraph].
type GraphOpts struct {
	// SinkDb mirrors the sink's graph into a DB from the start.
	SinkDb amtypes.DbGraph
	// MachinesPerNode is the number of source machines per node. Defaults to
	// [MachinesPerNode].
	MachinesPerNode int
	// Quiet disables printing the topology for large graphs.
	Quiet bool
	// NoRandomTags disables random src-id tags on source machines.
	NoRandomTags bool
	// WaitTimeout is the graph sync wait timeout. Defaults to 3s.
	WaitTimeout time.Duration
	// NetOpts are extra [amgraph.NetworkGraphOpts] applied to every node
	// (tests). Only Listener and Dial are honored.
	NetOpts amgraph.NetworkGraphOpts
}

// NewMachineGraph creates the supplied machine topology over UDP.
func (
	 *testing.T,  context.Context,  string,  ...GraphOpts,
) *MachineGraph {
	.Helper()

	 := GraphOpts{
		MachinesPerNode: MachinesPerNode,
		WaitTimeout:     3 * time.Second,
	}
	if len() > 0 {
		 = [0]
		if .MachinesPerNode == 0 {
			.MachinesPerNode = MachinesPerNode
		}
		if .WaitTimeout == 0 {
			.WaitTimeout = 3 * time.Second
		}
	}

	 := parseSpec(, )
	 := &MachineGraph{
		T:             ,
		ByID:          make(map[string]*NetNode),
		Children:      make(map[string][]*NetNode),
		RelayExpected: make(map[string][]*am.Machine),
		NodeMachines:  make(map[string][]*am.Machine),
		ctx:           ,
		waitTimeout:   .WaitTimeout,
	}
	.Cleanup(func() {
		for  := len(.Nodes) - 1;  >= 0; -- {
			_ = .Nodes[].Net.Close()
			for ,  := range .Nodes[].Machines {
				.Dispose()
			}
			.Nodes[].Server.Dispose()
		}
	})

	var  []string
	for ,  := range .Nodes {
		 = append(, machineIds(.ID, .MachinesPerNode)...)
	}

	 := func( string,  int) *NetNode {
		 := &NetNode{
			ID:         ,
			discovered: make(map[string]struct{}),
		}
		for ,  := range machineIds(, ) {
			 := am.New(, ssrel.States, &am.Opts{Id: })
			if  := .VerifyStates(ssrel.Names);  != nil {
				.Fatal()
			}

			// simulate a random RPC conn via a src-id tag, like real RPC
			// clients (pkg/rpc/rpc_client.go)
			if !.NoRandomTags {
				 := [rand.IntN(len())]
				if  !=  && rand.IntN(2) == 0 {
					.SetTags([]string{ssrpc.TagKeySrcId + ":" + })
				}
			}

			.Machines = append(.Machines, )
		}
		// TODO ssdbg.ServerSchema unnecessary, StateErrGraph only needed
		.Server = am.New(, ssdbg.ServerSchema, &am.Opts{Id: "srv-" + })
		var  error
		.Graph,  = amgraph.New(.Server)
		if  != nil {
			.Fatal()
		}
		// mirror the sink into the DB from the start, so no late attach races
		var  amtypes.DbGraph
		if  == .Root {
			 = .SinkDb
		}
		.Net,  = amgraph.NewNetworkGraph(, "127.0.0.1:0", .Graph,
			amgraph.NetworkGraphOpts{
				Db:           ,
				PushInterval: NetworkGraphPushInterval,
				Listener:     .NetOpts.Listener,
				Dial:         .NetOpts.Dial,
			})
		if  != nil {
			.Fatal()
		}
		.Nodes = append(.Nodes, )
		.ByID[] = 
		.NodeMachines[] = .Machines
		.Machines = append(.Machines, .Machines...)
		return 
	}

	.Sink = (.Root, 0)

	for ,  := range .Nodes {
		(.ID, .MachinesPerNode)
	}

	for ,  := range .Nodes {
		 := .ByID[.ID]
		 := .ByID[.Parent]
		.ParentID = .Parent
		.Net.EmitToAddr(.Net.Addr)
		.Children[.ID] = append(.Children[.ID], )
		if len(.Children[.ID]) > 0 {
			.Parents = append(.Parents, .ID)
		}
	}

	for ,  := range .Parents {
		for ,  := range .Children[] {
			.RelayExpected[] = append(.RelayExpected[],
				.Machines...)
		}
	}

	 := amhelp.SchemaHash(.Machines[0].Schema())
	 := amgraph.SchemaInfo{
		Schema:      .Machines[0].Schema(),
		StatesIndex: .Machines[0].StateNames(),
	}
	for ,  := range .Nodes {
		.Net.SchemaStore[] = 
	}

	if !.Quiet && len(.Nodes) <= 64 {
		printTopology()
	}

	for ,  := range .Nodes {
		for ,  := range .Machines {
			if ,  := .Net.TraceMach();  != nil {
				.Fatal()
			}
		}
	}

	 := slices.Index(.Machines[0].StateNames(), ssrel.B)
	if  < 0 {
		.Fatalf("state %s missing", ssrel.B)
	}
	.Idx = 

	return 
}

// AddState applies a state to every traced machine.
func ( *MachineGraph) ( string) {
	for ,  := range .Machines {
		.Add1(, nil)
	}
}

// WaitParents waits until every forwarding node mirrors its children.
func ( *MachineGraph) () {
	.T.Helper()
	for ,  := range .Parents {
		.WaitGraph(.ByID[].Graph, .RelayExpected[])
	}
}

// WaitSink waits until the sink mirrors all machines.
func ( *MachineGraph) () {
	.T.Helper()
	.WaitGraph(.Sink.Graph, .Machines)
}

// WaitGraph waits until all machines are present in a graph.
func ( *MachineGraph) ( *amgraph.Graph,  []*am.Machine) {
	.T.Helper()
	.wait(, , func( *amgraph.Machine) bool {
		return .Time.Is1(.Idx)
	})
}

// WaitTags waits until a sink client reflects the expected tags.
func ( *MachineGraph) ( string,  []string) {
	.T.Helper()

	 := time.Now().Add(3 * time.Second)
	for {
		if ,  := .Sink.Graph.Machine();  &&
			slices.Equal(.Tags, ) {
			return
		}
		if time.Now().After() {
			.T.Fatalf("timed out waiting for tags of %s", )
		}
		time.Sleep(10 * time.Millisecond)
	}
}

// WaitClients waits until all machines have any clock data in a graph.
func ( *MachineGraph) ( *amgraph.Graph,  []*am.Machine) {
	.T.Helper()
	.wait(, , func( *amgraph.Machine) bool {
		return .MTimeSum > 0
	})
}

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

// ///// DISCOVERY

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

// StartDiscovery starts one RPC server per node, advertises it as an #addr
// tag, and dials every #addr discovered through the local NetworkGraph. Every
// connection is a real TCP RPC client, mirrored as a CONNECTED_TO edge.
func ( *MachineGraph) ( ...DiscoveryOpts) {
	.T.Helper()

	 := DiscoveryOpts{}
	if len() > 0 {
		 = [0]
	}

	,  := context.WithCancel(.ctx)
	.Servers = make(map[string]*arpc.Server)

	// start the servers first, so all #addr tags can propagate at once
	for ,  := range .Nodes {
		if len(.Machines) == 0 {
			continue
		}
		 := .Machines[0]
		,  := arpc.NewServer(, "127.0.0.1:0", .ID, , nil)
		if  != nil {
			.T.Fatal()
		}
		.Start(nil)
		select {
		case <-.Mach.When1(ssrpc.ServerStates.RpcReady, ):
		case <-time.After(5 * time.Second):
			.T.Fatalf("rpc server %s did not start", .ID)
		}
		// advertise the TCP listener on the traced source machine
		amhelp.TagSetOnMach(, ssrpc.TagKeyAddr, .Addr)
		.Servers[.ID] = 
	}

	// precompute the source machines visible to each node
	.discoverySources = make(map[string][]string, len(.Nodes))
	for ,  := range .Nodes {
		.discoverySources[.ID] = .subtreeSources(.ID)
	}

	.discoveryWant = 0
	for ,  := range .Nodes {
		if .SinkOnly &&  != .Sink {
			continue
		}
		.discoveryWant += len(.discoverySources[.ID])
		.discoveryWg.Add(1)
		go .discoveryLoop(, )
	}

	.T.Cleanup(func() {
		()
		.discoveryWg.Wait()
		for ,  := range .Clients {
			if .NetMach != nil {
				.Stop(nil, nil, true)
			} else {
				.Mach.Dispose()
			}
		}
		for ,  := range .Servers {
			.Stop(nil, true)
		}
	})
}

// WaitDiscovery waits until the configured scope dialed all its descendants.
func ( *MachineGraph) ( time.Duration) {
	.T.Helper()

	 := .discoveryWant
	if  == 0 {
		for ,  := range .discoverySources {
			 += len()
		}
	}

	 := time.Now().Add()
	for {
		.discoveryMx.Lock()
		 := len(.Clients)
		.discoveryMx.Unlock()
		if  >=  {
			.T.Logf("discovered %d TCP RPC conns", )
			return
		}
		if time.Now().After() {
			.T.Fatalf("discovered %d/%d TCP RPC conns", , )
		}
		time.Sleep(10 * time.Millisecond)
	}
}

// subtreeSources returns the source machine IDs of all descendants of a node.
func ( *MachineGraph) ( string) []string {
	var  []string
	for ,  := range .Children[] {
		if len(.Machines) > 0 {
			 = append(, .Machines[0].Id())
		}
		 = append(, .(.ID)...)
	}
	return 
}

func ( *MachineGraph) ( context.Context,  *NetNode) {
	defer .discoveryWg.Done()

	 := time.NewTicker(NetworkGraphPushInterval)
	defer .Stop()

	for {
		select {
		case <-.Done():
			return
		case <-.C:
			for ,  := range .discoverySources[.ID] {
				.dialSource(, , )
			}
		}
	}
}

// dialSource connects to a source machine once its #addr tag is mirrored.
func ( *MachineGraph) (
	 context.Context,  *NetNode,  string,
) {
	if ,  := .discovered[];  {
		return
	}

	,  := .Graph.Machine()
	if ! {
		return
	}
	 := amhelp.TagValue(.Tags, ssrpc.TagKeyAddr)
	if  == "" {
		return
	}
	.discovered[] = struct{}{}

	,  := arpc.NewClient(, , "cl-"+.ID+"-"+, .Schema,
		&arpc.ClientOpts{Parent: .Server})
	if  != nil {
		.T.Logf("rpc client %s: %v", , )
		delete(.discovered, )
		return
	}
	.Start(nil)
	select {
	case <-.Mach.When1(ssrpc.ClientStates.HandshakeDone, ):
	case <-time.After(5 * time.Second):
		.Stop(nil, nil, true)
		delete(.discovered, )
		return
	case <-.Done():
		return
	}

	// the netmach carries the src-id tag, which becomes a CONNECTED_TO edge.
	// Only the sink mirrors its clients: its graph is the GQL source and it has
	// no downstream to relay late-bound netmach baselines to.
	if  == .Sink {
		if ,  := .Net.TraceMach(.NetMach);  != nil {
			.Stop(nil, nil, true)
			delete(.discovered, )
			return
		}
	}

	.discoveryMx.Lock()
	.Clients = append(.Clients, )
	.discoveryMx.Unlock()
}

func ( *MachineGraph) (
	 *amgraph.Graph,  []*am.Machine,  func(*amgraph.Machine) bool,
) {
	.T.Helper()

	 := time.Now().Add(.waitTimeout)
	for {
		 := true
		var  []string
		for ,  := range  {
			,  := .Machine(.Id())
			if ! || !() {
				 = false
				 = append(, .Id())
			}
		}
		if  {
			return
		}
		if time.Now().After() {
			.T.Fatalf("timed out waiting for graph updates: %v", )
		}
		time.Sleep(10 * time.Millisecond)
	}
}

// AssertSinkGraph validates the sink graph's machines, clocks, and relations.
func ( *MachineGraph) () {
	.T.Helper()

	,  := .Sink.Graph.Inspect()
	if  != nil {
		.T.Fatal()
	}
	if len() != len(.Machines) {
		.T.Fatalf("expected %d machines in sink graph, got %d",
			len(.Machines), len())
	}

	for ,  := range .Machines {
		,  := [.Id()]
		if ! {
			.T.Fatalf("missing machine %s in sink graph", .Id())
		}
		if !slices.Equal(.States, .StateNames()) {
			.T.Fatalf("%s: state index mismatch: %v != %v",
				.Id(), .States, .StateNames())
		}
		if len(.Schema) != len(.Schema()) {
			.T.Fatalf("%s: schema size mismatch", .Id())
		}
		if .MTimeSum == 0 {
			.T.Fatalf("%s: no clock updates in sink graph", .Id())
		}
	}

	 := .Machines[0].Id()
	,  := .Sink.Graph.Connection(, +":"+ssrel.A)
	if  != nil || .Edge.MachHas == nil {
		.T.Fatalf("%s: missing machine-state edge: %v", , )
	}
	,  = .Sink.Graph.Connection(
		+":"+ssrel.B, +":"+ssrel.C)
	if  != nil {
		.T.Fatalf("%s: missing B->C relation: %v", , )
	}
	 := false
	for ,  := range .Edge.StateRelation {
		if  != nil && .RelType == am.RelationAdd {
			 = true
			break
		}
	}
	if ! {
		.T.Fatalf("%s: B->C is not an add relation", )
	}
}

func printTopology( *MachineGraph) {
	var  strings.Builder
	.WriteString(.Sink.ID + "\n")
	for ,  := range .Children[.Sink.ID] {
		printNode(&, , , "",  == len(.Children[.Sink.ID])-1)
	}
	print(.String())
}

func printNode(
	 *strings.Builder,  *MachineGraph,  *NetNode,  string,
	 bool,
) {
	 := "├── "
	 :=  + "│   "
	if  {
		 = "└── "
		 =  + "    "
	}
	.WriteString( +  + .ID)
	printMachines(, .Machines)
	.WriteString("\n")

	 := .Children[.ID]
	for ,  := range  {
		(, , , ,  == len()-1)
	}
}

func printMachines( *strings.Builder,  []*am.Machine) {
	if len() == 0 {
		return
	}
	fmt.Fprintf(, " [%s..%s]", [0].Id(), [len()-1].Id())
}

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

// ///// SUITE

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

// RunDbMirrorSuite attaches db to f's sink, serves it over HTTP+JSON, triggers
// a fresh update burst, and asserts the mirrored model against the fixture.
// It's backend-agnostic, so any [amtypes.DbGraph] implementation can run it.
func ( *testing.T,  *MachineGraph,  amtypes.DbGraph) {
	.Helper()

	// mirror the sink's graph
	.Sink.Net.Db = 
	,  := .Sink.Net.StartDbHttpServer("127.0.0.1:0")
	if  != nil {
		.Fatal()
	}
	 := "http://" + 
	 := httpx.New()

	// trigger a fresh burst of updates, so every machine hits the DB
	.AddState(ssrel.D)

	// time queries and print elapsed
	 := func( string) []map[string]any {
		.Helper()
		 := time.Now()

		 := httpx.Post[string, []map[string]any](, +"/query", ,
			httpx.Header("Content-Type", "text/plain"))
		if .Err != nil {
			.Fatalf("query %q: %v", , .Err)
		}
		 := .Body

		.Logf("query %q: %s (%d rows)", , time.Since(), len())
		return 
	}

	 := func( string,  func() bool) {
		.Helper()
		 := time.Now().Add(10 * time.Second)
		for {
			if () {
				return
			}
			if time.Now().After() {
				.Fatalf("timed out waiting for %s", )
			}
			time.Sleep(10 * time.Millisecond)
		}
	}

	// all machines mirrored
	 := time.Now().Add(20 * time.Second)
	for {
		 := ("MATCH (m:Machine) RETURN m.id AS id")
		 := make([]string, 0, len())
		for ,  := range  {
			if ,  := ["id"].(string);  {
				 = append(, )
			}
		}
		if len() == len(.Machines) {
			break
		}
		if time.Now().After() {
			 := make([]string, 0, len(.Machines))
			for ,  := range .Machines {
				 = append(, .Id())
			}
			slices.Sort()
			slices.Sort()
			var  []string
			for ,  := range  {
				if !slices.Contains(, ) {
					 = append(, )
				}
			}
			.Fatalf("mirror incomplete: %d/%d, missing %v", len(),
				len(), )
		}
		time.Sleep(10 * time.Millisecond)
	}

	// states + relations per machine
	for ,  := range .Machines {
		 := "'" + .Id() + "'"
		 := (fmt.Sprintf(
			"MATCH (s:State {mach: %s}) RETURN s.name AS name", ))
		if len() != len(ssrel.Names) {
			.Fatalf("%s: %d states, want %d", .Id(), len(),
				len(ssrel.Names))
		}

		 = (fmt.Sprintf(
			"MATCH (m:Machine {id: %s})-[:HAS]->(s:State) RETURN s.name AS name",
			))
		if len() != len(ssrel.Names) {
			.Fatalf("%s: %d HAS edges, want %d", .Id(), len(),
				len(ssrel.Names))
		}
	}

	// RPC conns, as tagged by the fixture
	 := 0
	for ,  := range .Machines {
		for ,  := range .Tags() {
			if strings.HasPrefix(, ssrpc.TagKeySrcId+":") {
				++
				break
			}
		}
	}
	 := time.Now().Add(10 * time.Second)
	for {
		 := ("MATCH (a)-[:CONNECTED_TO]->(b) RETURN a.id AS id")
		if len() ==  {
			break
		}
		if time.Now().After() {
			 := ("MATCH (t:Tag) RETURN t.mach AS mach, t.name AS name")
			.Fatalf("rpc conns: %d/%d (tags: %d, sample: %v)", len(),
				, len(), [:min(len(), 5)])
		}
		time.Sleep(10 * time.Millisecond)
	}

	// serialized machine over HTTP, compared to the sink's mirror
	 := .Machines[0]
	("serialized clocks", func() bool {
		 := httpx.Get[am.Serialized](, +"/machine?id="+.Id())
		if .Err != nil {
			return false
		}
		 := .Body

		if .ID != .Id() || !slices.Equal(.StateNames, ssrel.Names) {
			.Fatalf("unexpected machine: %#v", )
		}
		 := slices.Clone(.Tags)
		 := slices.Clone(.Tags())
		slices.Sort()
		slices.Sort()
		if !slices.Equal(, ) {
			.Fatalf("%s: tags %v, want %v", .Id(), .Tags, .Tags())
		}

		,  := .Sink.Graph.Machine(.Id())
		if ! {
			return false
		}

		return slices.Equal(.Time, .Time)
	})

	// error path
	 := httpx.Post[string, []byte](, +"/query", "NOPE (",
		httpx.Header("Content-Type", "text/plain"))
	var  *httpx.HTTPError
	if !errors.As(.Err, &) ||
		.StatusCode != http.StatusBadRequest {
		.Fatalf("bad query: %v", .Err)
	}
}