import argparse
import asyncio
import logging

from library.python.vault_client.instances import Production as VaultClient
from logging.handlers import RotatingFileHandler

from saas.library.python.abc import AbcAPI
from saas.library.python.token_store import PersistentTokenStore
from saas.tools.devops.canary.writer.configs import ToolConfig
from saas.tools.devops.canary.writer.delivery import DeliveryManager
from saas.tools.devops.canary.writer.service import SaasServiceWrapper


def __load_tvm_secret(tvm_id: int, abc_group: int) -> str:
    meta_info = AbcAPI().get_tvm_meta_info(tvm_id, abc_group)

    yav_secret_id = meta_info['secret_uuid']
    yav_token = PersistentTokenStore.get_token_from_store_env_or_file('yav')
    yav_client = VaultClient(authorization=f'OAuth {yav_token}', decode_files=True)

    version = yav_client.get_version(yav_secret_id)
    return version['value']['client_secret']


def _parse_config() -> ToolConfig:
    parser = argparse.ArgumentParser()

    parser.add_argument('--service', type=str, required=True, help='SaaS service name')
    parser.add_argument('--ctype', type=str, required=True, help='SaaS service ctype')

    parser.add_argument('--saas-abc-group', type=str, default=664, help='ABC group, used for TVM meta info extraction')
    parser.add_argument('--saas-tvm-id', type=str, default=2011146, help='Source TVM id')
    parser.add_argument('--logbroker-tvm-id', type=str, default=2001059, help='Destination TVM id for lb streams')

    parser.add_argument('--logfile', type=str, default=None, help='Log file path')
    parser.add_argument('--logrotate-max-bytes', type=int, default=1024*1024*256,
                        help='Logrotate: max log file size in bytes')
    parser.add_argument('--logrotate-backup-count', default=2, type=int, help='Logrotate: backup count')
    parser.add_argument('--debug', action='store_true', help='Should show debug level logs or not')

    args = parser.parse_args()

    saas_tvm_secret = __load_tvm_secret(args.saas_tvm_id, args.saas_abc_group)

    return ToolConfig(
        args.service,
        args.ctype,

        args.saas_abc_group,
        args.saas_tvm_id,
        saas_tvm_secret,
        args.logbroker_tvm_id,

        args.logfile,
        args.logrotate_max_bytes,
        args.logrotate_backup_count,
        args.debug
    )


async def main() -> None:
    config = _parse_config()
    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
    )

    service = SaasServiceWrapper(config.service, config.ctype)
    manager = DeliveryManager(config, service)

    await manager.infinite_write()


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