#!/usr/bin/env python

"""PGSync bootstrap."""
import logging

import click

from pgsync import settings
from pgsync.sync import Sync
from pgsync.utils import (
    config_loader,
    MutuallyExclusiveOption,
    show_settings,
    validate_config,
)

logger = logging.getLogger(__name__)


@click.command()
@click.option(
    "--config",
    "-c",
    help="Schema config",
    type=click.Path(exists=True),
    default=settings.SCHEMA,
    show_default=True,
    cls=MutuallyExclusiveOption,
    mutually_exclusive=["s3_schema_url", "schema_url"],
)
@click.option(
    "--schema_url",
    help="URL for schema config",
    type=click.STRING,
    default=settings.SCHEMA_URL,
    show_default=True,
    cls=MutuallyExclusiveOption,
    mutually_exclusive=["config", "s3_schema_url"],
)
@click.option(
    "--s3_schema_url",
    help="S3 URL for schema config",
    type=click.STRING,
    default=settings.S3_SCHEMA_URL,
    show_default=True,
    cls=MutuallyExclusiveOption,
    mutually_exclusive=["config", "schema_url"],
)
@click.option("--host", "-h", help="PG_HOST override")
@click.option("--password", is_flag=True, help="Prompt for database password")
@click.option("--port", "-p", help="PG_PORT override", type=int)
@click.option(
    "--teardown",
    "-t",
    is_flag=True,
    help="Teardown database triggers and replication slots",
)
@click.option(
    "--no-create",
    "-nc",
    is_flag=True,
    help=(
        "Skip DDL statement for objects "
        "(Functions, Views & Replication slots) creation"
    ),
    default=False,
)
@click.option("--user", "-u", help="PG_USER override")
@click.option(
    "--verbose",
    "-v",
    is_flag=True,
    default=False,
    help="Turn on verbosity",
)
def main(
    teardown: bool,
    config: str,
    schema_url: str,
    s3_schema_url: str,
    user: str,
    password: bool,
    host: str,
    port: int,
    verbose: bool,
    no_create: bool = False,
) -> None:
    """Application onetime bootstrap."""
    kwargs: dict = {
        "user": user,
        "host": host,
        "port": port,
    }
    if password:
        kwargs["password"] = click.prompt(
            "Password",
            type=str,
            hide_input=True,
        )
    kwargs = {key: value for key, value in kwargs.items() if value is not None}

    validate_config(
        config=config,
        schema_url=schema_url,
        s3_schema_url=s3_schema_url,
    )

    show_settings(
        config=config,
        schema_url=schema_url,
        s3_schema_url=s3_schema_url,
        **kwargs,
    )

    validate: bool = False if teardown else True

    for doc in config_loader(
        config=config, schema_url=schema_url, s3_schema_url=s3_schema_url
    ):
        sync: Sync = Sync(
            doc,
            verbose=verbose,
            validate=validate,
            repl_slots=False,
            **kwargs,
        )
        if teardown:
            sync.teardown()
            continue
        sync.setup(no_create=no_create)
        logger.info(f"Bootstrap: {sync.database}")


if __name__ == "__main__":
    main()
