import asyncio
import logging

from logging.handlers import RotatingFileHandler

from saas.library.python.zk import ZKClient
from saas.tools.devops.lb_dc_checker.dc_checker import AppConfig, DatacenterChecker, LogbrokerClusterChecker


async def main() -> None:
    config = AppConfig.parse_args()
    logging.basicConfig(
        handlers=[
            RotatingFileHandler(
                config.logfile,
                maxBytes=config.logrotate_max_bytes,
                backupCount=config.logrotate_backup_count
            )
        ] if config.logfile else None,
        level=logging.DEBUG if config.debug else logging.INFO,
        format='%(asctime)s | %(levelname)-7s | %(message)s',
        datefmt='%H:%M:%S',
        force=True
    )

    zk_client = ZKClient()
    async with zk_client:
        lock = zk_client.create_write_lock(config.zk_base_path)
        acquired = lock.acquire(blocking=True, ephemeral=True)

        if acquired:
            lb_cluster_checker = LogbrokerClusterChecker()
            dc_checker = DatacenterChecker(config, lb_cluster_checker, zk_client)

            await asyncio.gather(*[dc_checker.run(), lb_cluster_checker.run()])


if __name__ == '__main__':
    asyncio.run(main())
