#!python

"""PGSync bootstrap."""
import json
import logging

import click

from pgsync.sync import Sync
from pgsync.utils import get_config

logger = logging.getLogger(__name__)


@click.command()
@click.option(
    '--teardown',
    '-t',
    is_flag=True,
    help='Teardown database triggers and replication slots'
)
@click.option('--password', is_flag=True, help='Prompt for database password')
@click.option('--user', '-u', help='PG_USER overide')
@click.option('--host', '-h', help='PG_HOST overide')
@click.option('--port', '-p', help='PG_PORT overide', type=int)
@click.option('--config', '-c', help='Schema config')
def main(teardown, config, user, password, host, port):
    """Application onetime Bootstrap."""
    pg_params = {
        'user': user,
        'host': host,
        'port': port,
    }
    if password:
        pg_params['password'] = click.prompt(
            "Password",
            type=str,
            hide_input=True,
        )
    pg_params = {
        key: value for key, value in pg_params.items() if value is not None
    }

    config = get_config(config)

    for document in json.load(open(config)):

        sync = Sync(document, **pg_params)

        if teardown:
            sync.teardown()
            continue

        sync.setup()
        logger.info(f'Bootstrap: {sync.database}')


if __name__ == '__main__':
    main()
