import click
import json
import logging

from aiohttp import web
from logging.handlers import RotatingFileHandler
from typing import Optional

from saas.tools.devops.canary.reader.app import AppMaker
from saas.tools.devops.canary.reader.configs import AppConfig


def _load_config(config_path: str) -> AppConfig:
    with open(config_path, 'r') as f:
        config_data = json.load(f)

    return AppConfig.parse(config_data)


@click.command('canary_reader')
@click.option('--config-path', default='configs/settings.json', help='A path to the app config file in json format')
@click.option('--logfile', default=None, help='Log file path')
@click.option('--logrotate-max-bytes', type=int, default=1024*1024*256, help='Logrotate: max log file size in bytes')
@click.option('--logrotate-backup-count', type=int, default=2, help='Logrotate: backup count')
def main(config_path: str, logfile: Optional[str], logrotate_max_bytes: int, logrotate_backup_count: int) -> None:
    config = _load_config(config_path)
    logging.basicConfig(
        handlers=[
            RotatingFileHandler(
                logfile,
                maxBytes=logrotate_max_bytes,
                backupCount=logrotate_backup_count
            )
        ] if 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
    )

    app = AppMaker(config).make_app()
    web.run_app(app, port=config.server_port)


if __name__ == '__main__':
    main()
