import argparse
import json
import logging
import os
import sys
from maps.pylibs import staff
from maps.wikimap.stat.tasks_payment.dictionaries.staff_dump.lib import staff_dump


STAFF_TOKEN_NAME = 'STAFF_TOKEN'
CLIENT_ID = '4e1c56227137461c8001db61232660ab'
AUTH_URL_FMT = 'https://oauth.yandex-team.ru/authorize?response_type=token&client_id={client_id}'


def parse_args():
    parser = argparse.ArgumentParser(
        description='Retrieve json records from staff-api/v3 endpoints.\n'
        '\n'
        '{token} must be specified in environment. Obtain token for staff-api on\n'
        '{auth_url}.'.format(
            token=STAFF_TOKEN_NAME,
            auth_url=AUTH_URL_FMT.format(client_id=CLIENT_ID),
        ),
        formatter_class=argparse.RawTextHelpFormatter,
        epilog='See staff API docs at {}'.format(staff.DOCS_URL)
    )
    parser.add_argument(
        '--departments',
        metavar='DEPARTMENT',
        help='List of departments to dump (separated by space).\n'
        'Departments are defined by corresponding Staff URL:\n'
        'https://staff.yandex-team.ru/departments/<DEPARTMENT>.',
        required=True,
        nargs='+'
    )
    parser.add_argument(
        '--log-level',
        help='Logging level.',
        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'],
        default='INFO'
    )
    return parser.parse_args()


def get_logger(log_level):
    logging.basicConfig(
        level=log_level,
        format='%(asctime)s %(levelname)s %(message)s'
    )
    return logging.getLogger("main-logger")


def get_token(logger):
    if STAFF_TOKEN_NAME not in os.environ:
        logger.error('Environment variable %s is not set', STAFF_TOKEN_NAME)
        sys.exit(os.EX_USAGE)
    return str(os.environ[STAFF_TOKEN_NAME])


def get_staff(log_level):
    logger = get_logger(log_level)
    token = get_token(logger)
    return staff.Staff(token, logger)


def main():
    args = parse_args()
    staff = get_staff(args.log_level)
    for record in staff_dump.dump_persons(staff, set(args.departments)):
        print(json.dumps(record, ensure_ascii=False))
