#!/usr/bin/env python3

import argparse
import getpass
import json
import logging
import sys

from githubcollaborators import githubcollaborators


def main():
    parser = argparse.ArgumentParser(
        description="""List collaborators for all repositories for the given
        user. Might take a while to run, be patient."""
    )
    parser.add_argument(
        "-u",
        "--username",
        required=True,
        help="GitHub username"
    )
    parser.add_argument(
        "-t",
        "--token",
        required=False,
        help="""Personal Access Token for the specified GitHub username.
            Requires following permissions: repo("Full control of private
            repositories"), admin: org -> read: org("Read or and team
            membership, read org projects"), user -> read: user("Read all user
            profile data")"""
    )
    parser.add_argument(
        "-v",
        "--visibility",
        required=False,
        help="Visibility level of the repositories, can be: all, public, or private"
    )
    parser.add_argument(
        "-o",
        "--output",
        required=False,
        help="Save to specified output file"
    )
    parser.add_argument(
        "--verbose",
        action="store_true",
        help="Set logging level to INFO"
    )

    args = parser.parse_args()

    # Logging config
    logger = logging.getLogger("githubcollaborators")
    if args.verbose:
        logger.setLevel(logging.INFO)
    else:
        logger.setLevel(logging.ERROR)
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(logging.Formatter("[%(levelname)s]: %(message)s"))
    logger.addHandler(handler)

    token = getpass.getpass(
        "GitHub Personal Access Token:") if args.token is None else args.token

    repos_with_collaborators = githubcollaborators(
        args.username, token, logger_obj=logger)

    if args.output is not None:
        with open(args.output, "w") as f:
            json.dump(repos_with_collaborators, f, indent=2, sort_keys=True)
    else:
        print(json.dumps(repos_with_collaborators, indent=2, sort_keys=True))


if __name__ == "__main__":
    main()
