#!/usr/bin/env python

import os
import sys
import click
import logging
from cfn_sphere.util import convert_file, get_logger
from cfn_sphere.stack_config import StackConfig
from cfn_sphere.main import StackActionHandler

LOGGER = get_logger(root=True)


@click.group(help="This tool manages AWS CloudFormation templates "
                  "and stacks by providing an application scope and useful tooling.")
def cli():
    pass


@cli.command(help="Create an applications infrastructure")
@click.argument('filename', type=click.Path(exists=True))
@click.option('--debug', is_flag=True, default=False, help="Debug output")
@click.option('--confirm', is_flag=True, default=False, help="Override user confirm dialog with yes")
def sync(filename, debug, confirm):
    if debug:
        LOGGER.setLevel(logging.DEBUG)
    else:
        LOGGER.setLevel(logging.INFO)

    if confirm or click.confirm(
            'This tool will modify your infrastructure according to the configuration in {}. Are you sure='.format(
                filename), abort=True):
        try:
            working_dir = os.path.dirname(os.path.realpath(filename))

            stack_config = StackConfig(filename)
            StackActionHandler(stack_config, working_dir).create_or_update_stacks()
        except Exception as e:
            LOGGER.error("Error syncing {0}:".format(filename))
            LOGGER.error(e)
            sys.exit(1)


@cli.command(help="Convert JSON to YAML or vice versa")
@click.argument('filename', type=click.Path(exists=True))
@click.option('--debug', is_flag=True, default=False, help="Debug output")
def convert(filename, debug):
    if debug:
        LOGGER.setLevel(logging.DEBUG)

    try:
        click.echo(convert_file(filename))
    except Exception as e:
        LOGGER.error("Error converting {0}:".format(filename))
        LOGGER.error(e)
        sys.exit(1)


if __name__ == '__main__':
    cli()
