import os
import sys
import click
from datacloud.config.token_names import AUDIENCE_TOKEN_NAME
from datacloud.dev_utils.logging.logger import get_basic_logger
from datacloud.dev_utils.yt import yt_utils
from datacloud.audience.lib.config_table import AudienceConfigTable
from datacloud.audience.lib import upload as upload_util

logger = get_basic_logger(__name__)


@click.group()
def cli():
    pass


def upload_single_audience(yt_client, audience_table, audience, date):
    a = audience_table.get_audience(audience)
    logger.info('Audience is: {}'.format(a))
    assert a is not None, 'Unknown audience, {}'.format(audience)
    upload_util.upload_audience(yt_client, a, date)


@cli.command('upload')
@click.option('--audience')
@click.option('--date', required=True)
@click.option('--file', 'filename')
def upload(audience, date, filename):
    yt_client = yt_utils.get_yt_client()
    token = os.environ.get(AUDIENCE_TOKEN_NAME)
    assert token, 'No token provided'

    table = AudienceConfigTable(yt_client)

    if audience is not None:
        upload_single_audience(yt_client, table, audience, date)
    elif filename is not None:
        with open(filename, 'r') as fh:
            for line in fh:
                audience = line.strip()
                if not audience:
                    continue
                upload_single_audience(yt_client, table, audience, date)
    else:
        logger.error('Provide `--audience` or `--filename`')
        sys.exit(1)

if __name__ == '__main__':
    cli()
