#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2016 Robin Schneider <ypid@riseup.net>

__license__ = 'GPL-3.0'
__author__ = 'Robin Schneider <ypid@riseup.net>'
__version__ = '0.1.0'
SCRIPT_URL = 'https://github.com/debops/docs/blob/master/docs/docs/_bin/gen_rst_defs_using_debops_api'

"""
Generate URL definitions based on data returned by the DebOps API.
"""

import json
import logging
import urllib.request

if __name__ == '__main__':
    from argparse import ArgumentParser

    args_parser = ArgumentParser(
        description=__doc__,
    )
    args_parser.add_argument(
        '-V', '--version',
        action='version',
        version='%(prog)s {version}'.format(version=__version__)
    )
    args_parser.add_argument(
        '-d', '--debug',
        help="Print lots of debugging statements.",
        action='store_const',
        dest='loglevel',
        const=logging.DEBUG,
        default=logging.WARNING,
    )
    args_parser.add_argument(
        '-v', '--verbose',
        help="Be verbose.",
        action='store_const',
        dest='loglevel',
        const=logging.INFO,
    )
    args_parser.add_argument(
        '-i', '--debops-api-response-file',
        help="Use the provided file instead of making an DebOps API query.",
    )
    args_parser.add_argument(
        '-q', '--debops-api-query',
        help="Make the given DebOps API query and create RST definitions based"
        " on it’s response.",
    )
    args_parser.add_argument(
        '-a', '--debops-api-url',
        help="DebOps API URL. Defaults to %(default)s",
        default="https://api.debops.org",
    )
    args_parser.add_argument(
        '-o', '--role-owner',
        help="Role owner of the RST definitions to output.",
        required=True,
    )
    args = args_parser.parse_args()

    logger = logging.getLogger(__file__)
    logging.basicConfig(
        format='%(levelname)s: %(message)s',
        level=args.loglevel,
    )

    role_owner = args.role_owner
    debops_api_response = {}
    if args.debops_api_response_file:
        with open(args.debops_api_response_file, 'r') as api_rsp_fh:
            debops_api_response = json.load(api_rsp_fh)

    if args.debops_api_query:
        url = args.debops_api_url + '/' + args.debops_api_query
        logger.info("Loading API data from: {}".format(url))
        req = urllib.request.urlopen(url)
        debops_api_response = json.loads(req.read().decode())

    print(".. {} roles [[[".format(role_owner))
    print(".. This section was generated by: {}".format(SCRIPT_URL))
    print("")

    logger.debug("Roles: {}".format(debops_api_response.keys()))

    for role_full_name, metadata in sorted(debops_api_response.items()):
        print('.. _{role_owner}.{role_name}: {vcs_url}'.format(
            role_owner=metadata['role_owner'],
            role_name=metadata['role_name'],
            vcs_url=metadata['vcs_url'],
        ))

    print("")

    for role_full_name, metadata in sorted(debops_api_response.items()):
        if 'docs_url' in metadata:
            print('.. _{role_owner}.{role_name} documentation: {vcs_url}'.format(
                role_owner=metadata['role_owner'],
                role_name=metadata['role_name'],
                vcs_url=metadata['docs_url'],
            ))
    print(".. ]]]")
