package repl

import (
	
	
	
	
	
	
	

	am 
	ssrpc 
)

// clients returns a snapshot of the registered clients.
func ( *Repl) () []*replClient {
	.clientsMu.RLock()
	defer .clientsMu.RUnlock()

	return slices.Clone(.rpcClients)
}

// addrs returns a snapshot of the registered named addresses.
func ( *Repl) () []NamedAddr {
	.clientsMu.RLock()
	defer .clientsMu.RUnlock()

	return slices.Clone(.Addrs)
}

// clientName returns the name of a client by its local machine ID.
func ( *Repl) ( string) string {
	for ,  := range .clients() {
		if .Mach.Id() ==  {
			return .Name
		}
	}

	return 
}

// countReady returns the number of ready clients.
func countReady( []*replClient) int {
	 := 0
	for ,  := range  {
		if .Mach.Is1(ssrpc.ClientStates.Ready) {
			++
		}
	}

	return 
}

// connStatus returns the aggregate connection status of a pool.
func connStatus(,  int) (,  bool) {
	return  > 0,  > 0 &&  == 
}

// isShuttingDown reports whether the current transition tears the REPL down.
func isShuttingDown( *am.Event) bool {
	if  == nil {
		return false
	}

	 := .Transition().TargetStates()
	 := .Mutation()
	 := .Machine().Index1(ss.Start)

	return slices.Contains(, ss.Disconnected) ||
		slices.Contains(, ss.Disconnecting) ||
		// dont block a restart
		(.Type == am.MutationRemove && .IsCalled())
}

// updateConnStates recomputes the aggregate ConnPool states from the clients.
func ( *Repl) () {
	 := .clients()
	,  := connStatus(countReady(), len())

	if  {
		.Mach.Add1(ss.Connected, nil)
	} else {
		.Mach.Remove1(ss.Connected, nil)
	}

	if  {
		.Mach.Add1(ss.ConnectedFully, nil)
	} else {
		.Mach.Remove1(ss.ConnectedFully, nil)
	}
}

// planReconcile matches existing clients to new addresses, keeping clients
// which keep their name+addr, or only their addr (eg after a file rename).
// The returned slice is indexed like addrs, with nil for new addresses.
func planReconcile(
	 []*replClient,  []NamedAddr,
) ( []*replClient,  []*replClient) {
	 := make(map[string]*replClient, len())
	 := make(map[string]*replClient, len())
	for ,  := range  {
		[.Name] = 
		[.Addr] = 
	}

	 := make(map[*replClient]bool, len())
	 = make([]*replClient, len())
	for ,  := range  {

		// keep by name
		if  := [.Name];  != nil && ![] && .Addr == .Addr {
			[] = 
			[] = true
			continue
		}

		// keep by addr, eg a renamed address file
		if  := [.Addr];  != nil && ![] {
			[] = 
			[] = true
			continue
		}
	}

	for ,  := range  {
		if ![] {
			 = append(, )
		}
	}

	return , 
}

// renameClient returns a client with a new name, keeping the same connection.
// It never mutates the passed client, so concurrent readers stay race-free.
func renameClient( *replClient,  string) *replClient {
	if .Name ==  {
		return 
	}

	return &replClient{Name: , Client: .Client}
}

// manualAddrs returns manually added addresses.
func manualAddrs( []NamedAddr) []NamedAddr {
	 := make([]NamedAddr, 0, len())
	for ,  := range  {
		if .Manual {
			 = append(, )
		}
	}

	return 
}

// mergeManualAddrs appends manual addresses missing from the watched list.
func mergeManualAddrs(,  []NamedAddr) []NamedAddr {
	 := slices.Clone()
	 := make(map[string]bool, len()+len())
	for ,  := range  {
		[.Addr] = true
	}
	for ,  := range  {
		if [.Addr] {
			continue
		}
		[.Addr] = true
		 = append(, )
	}

	return 
}

// validateConnectAddr validates a host:port address with an optional WebSocket
// path suffix, eg localhost:6452/ws.
func validateConnectAddr( string) error {
	 := 
	if  := strings.IndexByte(, '/');  >= 0 {
		 = [:]
	}

	, ,  := net.SplitHostPort()
	if  != nil ||  == "" ||  == "" {
		return fmt.Errorf("invalid address: %s", )
	}

	return nil
}

// nextCLIName returns the next free CLI<N> name.
func nextCLIName( []NamedAddr) string {
	 := make(map[string]bool, len())
	for ,  := range  {
		[.Name] = true
	}
	for  := 0; ; ++ {
		 := "CLI" + strconv.Itoa()
		if ![] {
			return 
		}
	}
}

// connectAddr adds and starts a new client, or returns an existing one for the
// same address. Added clients are marked manual and survive watcher updates.
func ( *Repl) ( *am.Event,  string) (
	*replClient, bool, error,
) {
	.clientsMu.Lock()
	for ,  := range .rpcClients {
		if .Addr ==  {
			.clientsMu.Unlock()
			return , false, nil
		}
	}

	 := NamedAddr{
		Name:   nextCLIName(.Addrs),
		Addr:   ,
		Manual: true,
	}
	.clientSeq++
	,  := .newRpcClient(, strconv.Itoa(.clientSeq))
	if  != nil {
		.clientsMu.Unlock()
		return nil, false, 
	}
	.rpcClients = append(.rpcClients, )
	.Addrs = append(.Addrs, )
	.clientsMu.Unlock()

	.Start()
	.updateConnStates()

	return , true, nil
}

// reconcileClients applies a new address list, keeping existing clients for
// unchanged addresses and stopping only removed ones.
func ( *Repl) ( *am.Event,  []NamedAddr) {
	.clientsMu.Lock()
	// watched updates must not drop manually connected machines
	 = mergeManualAddrs(, manualAddrs(.Addrs))
	,  := planReconcile(.rpcClients, )

	 := make([]*replClient, 0, len())
	 := make([]*replClient, 0)
	for ,  := range  {
		if [] != nil {
			 = append(, renameClient([], .Name))
			continue
		}

		.clientSeq++
		,  := .newRpcClient(, strconv.Itoa(.clientSeq))
		if  != nil {
			.Mach.EvAddErr(, , nil)
			continue
		}
		 = append(, )
		 = append(, )
	}

	.rpcClients = 
	.Addrs = 
	.clientsMu.Unlock()

	// start only the new clients
	for ,  := range  {
		.Start()
	}
	// stop removed clients outside the lock
	for ,  := range  {
		.stopClient()
	}

	.updateConnStates()
}

// stopClient gracefully disconnects and disposes a removed client.
func ( *Repl) ( *replClient) {
	go func() {
		,  := context.WithTimeout(context.Background(), 3*time.Second)
		defer ()

		if .NetMach == nil {
			.Mach.Dispose()
			return
		}
		.Stop(, nil, true)
	}()
}

// clientStatus is a named client connection status.
type clientStatus struct {
	Name  string
	Addr  string
	State string
}

// clientStatuses returns the status of all registered clients.
func ( *Repl) () []clientStatus {
	 := .clients()
	 := make([]clientStatus, 0, len())
	for ,  := range  {
		 := "disconnected"
		switch {
		case .Mach.Is1(ssrpc.ClientStates.Ready):
			 = "connected"
		case .Mach.Is1(ssrpc.ClientStates.RetryingConn):
			 = "retrying"
		case .Mach.Is1(ssrpc.ClientStates.Connecting):
			 = "connecting"
		}
		 = append(, clientStatus{
			Name:  .Name,
			Addr:  .Addr,
			State: ,
		})
	}

	return 
}