#!/usr/bin/env python3
"""
wikiversions-for-dblist -- versions in use per dblist.

Does the exact same thing in the exact same way as
<https://tools.wmflabs.org/versions/>. In fact, the only reason to use this is
for a check for the labs version tool. If you're pretty sure that tool is
saying something wrong, this will be wrong in mostly the exact same ways except
for caching and running on the command line rather than on the labs infra; in
almost every other regard this tool is much worse.

Usage:
    wikiversions-for-dblist <dblist>
"""

import argparse
import os
import requests


def clean(line):
    return line.strip().strip(',"')


def conf_file(file):
    r = requests.get('https://noc.wikimedia.org/conf/{}'.format(file))
    r.raise_for_status()
    return r.text


def get_dblist(list_name):
    if not list_name.endswith('.dblist'):
        list_name = '{}.dblist'.format(list_name)

    raw_list = conf_file(os.path.join('dblists', list_name))

    final_list = set()

    for line in raw_list.splitlines():
        line = line.split('#')[0]

        if not line:
            continue

        if line.startswith('%% '):
            line = eval_dblists(line)
            final_list |= line
            continue

        final_list.add(line)

    return final_list


def eval_dblists(line):
    line = line[2:].strip()
    tokens = line.split(' ')
    final_list = get_dblist(tokens[0].strip())
    i = 1

    while i < len(tokens):
        token = tokens[i].strip()
        if token == '+':
            final_list |= get_dblist(tokens[i + 1])
        if token == '-':
            final_list = final_list.difference(get_dblist(tokens[i + 1]))

        i += 1

    return final_list


def get_active_wikiversions():
    active_versions = {}
    for line in conf_file('wikiversions.json').splitlines():
        if ':' not in line:
            continue

        wiki, version = line.split(':')

        active_versions[clean(wiki)] = clean(version)
    return active_versions


def parse_args():
    ap = argparse.ArgumentParser(
        usage='wikiversionsfordblist [group0|group1|all]',
        description=__doc__,
        formatter_class=argparse.RawTextHelpFormatter)
    ap.add_argument('-v', '--verbose', action='store_true',
                    help="Show wikis and versions")
    ap.add_argument('dblist', help='dblist to check for versions')
    return ap.parse_args()


if __name__ == '__main__':
    args = parse_args()
    dblist_name = args.dblist
    dblist = get_dblist(dblist_name)
    active_wikiversions = get_active_wikiversions()
    dblist_versions = set()

    for wiki in dblist:
        if args.verbose:
            print('{} -> {}'.format(wiki, active_wikiversions[wiki]))
        dblist_versions.add(active_wikiversions[wiki])

    print('DBList "{}" uses version(s)'.format(dblist_name))
    for version in dblist_versions:
        print('- {}'.format(version))
