import sys
import logging
import zmq
import pymoku
# jsonrpcserver<5 included in firmware
import jsonrpcserver as rpc


__version__ = '1.0'
INSTR_ID = sys.argv[1]
SLOT = int(sys.argv[2])

logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(f'slot{SLOT:d}-rpc')


@rpc.method
def get_info(instr):
    data = dict(version=__version__,
                instrid=INSTR_ID,
                slot=instr.slot,
                hw=type(instr.moku).__name__,
                serial=instr.moku.serial)
    return data


@rpc.method
def dump_regs(instr):
    return instr.dump_regs()


def serve(instr, addr):
    skt = zmq.Context().socket(zmq.REP)
    skt.bind(addr)

    while True:
        req = skt.recv_string()
        log.debug(req)
        skt.send_string(str(rpc.dispatch(req, context=instr)))


def main():
    log.info(f'starting {INSTR_ID}:{SLOT:d}')

    # We can't rely on pymoku's plugin loading, as it needs python>=3.10
    # but we're already 'in' the plugin, se we can load things manually.
    moku = pymoku.connect_ipc(attach=False)

    # constructing the instrument directly assumes it has been deployed already
    from __pymoku_plugin import Plugin
    m = dict(slot=SLOT)  # TODO one day the manifest may do more here
    slot = Plugin().attach(moku, manifest=m)

    from __pymoku_plugin import api

    addr = f'ipc://./instr{SLOT:d}'
    log.info(f'serving {type(slot).__name__} @ {addr}')
    serve(slot, addr)


main()
