//go:build !tinygo

package rpc

import (
	
	
	
	
	
	
	
	
	

	
	

	
	amhelp 
	am 
)

func listenTCP(
	 context.Context, ,  string,
) (net.Listener, error) {
	 := net.ListenConfig{}
	return .Listen(, , )
}

// dialWebSocket dials a WebSocket endpoint and returns a net.Conn carrying
// binary messages as a byte stream. Regular builds use coder/websocket.
func dialWebSocket(
	 context.Context,  string,  []string,  time.Duration,
) (net.Conn, error) {
	,  := context.WithTimeout(, )
	defer ()

	, ,  := websocket.Dial(, , &websocket.DialOptions{
		Subprotocols: ,
	})
	if  != nil {
		if .Err() != nil {
			return nil, .Err()
		}

		return nil, 
	}

	return websocket.NetConn(, , websocket.MessageBinary), nil
}

func ( *Client,  *am.Machine) (string, error) {
	return .HandlersBind()
}

func ( *Server,  *am.Machine) (string, error) {
	return .HandlersBind()
}

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

// ///// NETWORK MACHINE

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

func newHandler(
	 any,  string,  *reflect.Value,
) *handler {
	return &handler{
		id:           ,
		h:            ,
		methods:      ,
		methodCache:  make(map[string]reflect.Value),
		missingCache: make(map[string]struct{}),
	}
}

// HandlersBind binds a struct of handler methods to machine's states, based on
// the naming convention, eg `FooState(e *Event)`. Negotiation handlers can
// optionally return bool.
//
// # NetworkMachine
//
// NetworkMachine supports only pipe handlers (final ones, without negotiation).
func ( *NetworkMachine) (
	 any,  ...am.BindOpts,
) (string, error) {
	 := reflect.ValueOf()
	if .Kind() != reflect.Pointer || .Elem().Kind() != reflect.Struct {
		return "", errors.New("BindTracer expects a pointer to a struct")
	}
	.handlersMx.Lock()
	defer .handlersMx.Unlock()

	 := optBindOpts()
	// TODO name from stack trace
	 := "anon" + amhelp.RandId(4)
	if .Id != "" {
		 = idRe.ReplaceAllString(.Id, "")
	}
	 := .nextHandlerNum
	.nextHandlerNum++
	 := newHandler(, , &)
	.num = 
	.handlers = append(.handlers, )
	.log(am.LogOps, "[handlers] bind %d:%s", len(.handlers)-1, )

	return , nil
}

// handle runs a single handler method (currently only pipes).
func ( *NetworkMachine) ( *handler,  int, ,  string) {
	.mx.Lock()
	 :=  + 
	 := am.NewEvent(nil, )
	.Name = 
	.MachineId = .remoteId

	// TODO descriptive name
	 := strconv.Itoa() + ":" + .id

	if .semLogger.Level() >= am.LogEverything {
		 := utils.TruncateStr(, 15)
		 = utils.PadString(strings.ReplaceAll(
			, " ", "_",
		), 15, "_")
		.log(am.LogEverything, "[handle:%-15s] %s", , )
	}

	// map-based handlers
	if .isMap {
		.handleMap(, , , , )
		.mx.Unlock()
		return
	}

	// cache
	,  := .missingCache[]
	if  {
		.mx.Unlock()

		return
	}
	,  := .methodCache[]
	if ! {
		 = .methods.MethodByName()

		// support field handlers
		if !.IsValid() {
			 = .methods.Elem().FieldByName()
		}
		if !.IsValid() {
			.missingCache[] = struct{}{}
			.mx.Unlock()
			return
		}
		.methodCache[] = 
	}

	// call the handler (pipes dont block)
	.log(am.LogOps, "[handler:%d] %s", .num, )

	// tracers
	// m.tracersMx.RLock()
	 := .t.Load()
	for  := range .tracers {
		.tracers[].HandlerStart(, , )
	}
	// m.tracersMx.RUnlock()

	// call TODO should go-fork to avoid nested deadlocks?
	_ = .Call([]reflect.Value{reflect.ValueOf()})

	// tracers
	// m.tracersMx.RLock()
	for  := range .tracers {
		.tracers[].HandlerEnd(, , )
	}
	// m.tracersMx.RUnlock()

	// locks
	.mx.Unlock()
}

// rpcServer and rpcClient alias the rpc2 implementation for regular builds.
type (
	rpcServer = rpc2.Server
	rpcClient = rpc2.Client
)

func newRpcServer() *rpcServer {
	return rpc2.NewServer()
}

func newRpcClient( net.Conn) *rpcClient {
	return rpc2.NewClient()
}

func setRpcDebugLog( bool) {
	rpc2.DebugLog = 
}

// WEBSOCKET SERVER (not tunnel)

type wsHandlerServer struct {
	s     *Server
	event *am.Event
}

// ServeHTTP continues [Server.RpcStartingState].
func ( *wsHandlerServer) ( http.ResponseWriter,  *http.Request) {
	 := .s.Mach

	// origin is checked in [Server.newWebsocketHandler]
	,  := websocket.Accept(, , &websocket.AcceptOptions{
		InsecureSkipVerify: true,
	})
	if  != nil {
		log.Printf("Upgrade error: %v", )
		return
	}
	 := websocket.NetConn(.Context(), , websocket.MessageBinary)
	.s.Conn = 

	// next and stay alive TODO JSON-RPC compat via RpcAcceptingJson
	// TODO add Opts.JsonRpc (req Opts.WebSocket)
	.EvAdd1(.event, ssS.RpcAccepting, nil)
	select {
	case <-.WhenNot1(ss.Start, nil):
	case <-.Context().Done():
	}
}