#!/usr/bin/env python3

import sys
import asyncio
import signal
import logging
from concurrent import (
    futures,
)
from grpc import (
    aio,
)
from netops import (
    automation_gateway as ag,
)
from central_ag import (
    publishd,
    devices_names,
)


async def _main(
        *,
        executor: futures.Executor,
) -> int:
    logging.basicConfig(stream=sys.stderr, level=logging.INFO)
    logger = logging.getLogger()

    async with aio.insecure_channel('ag-devices:9047') as channel:
        daemon = publishd.Daemon(
            logger=logger,
            ag_devices=ag.DevicesStub(channel),
            device_names=devices_names.AIO(executor=executor),
        )

        def signal_handler(sig, _):
            daemon.done.close()

        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)

        await daemon.run()

    return 0


def main() -> int:
    with futures.ThreadPoolExecutor() as executor:
        return asyncio.run(_main(
            executor=executor,
        ))


if __name__ == '__main__':
    sys.exit(main())
