#!/usr/bin/python

import sys
import debianbts as bts
import yaml


def parse_transitions(yfile):
    t2s = {}
    with open(yfile) as f:
        data = yaml.safe_load(f)
        for srcdata in data:
            src = srcdata['name']
            l = srcdata['list']
            for ld in l:
                if ld[1] in ('finished', 'permanent'):
                    continue
                if ld[0] not in t2s:
                    t2s[ld[0]] = []
                t2s[ld[0]].append(src)
    return t2s

def get_bugs(sources):
    allbugs = set()
    for s in sources:
        allbugs.update(bts.get_bugs('src', s, 'status', ['open', 'forwarded'],  \
                                     'severity', ['serious', 'grave', 'critical']))
    return sorted(allbugs)

if __name__ == '__main__':
    yfile = sys.argv[1]
    fmethod = None
    if len(sys.argv) >= 3:
        check = frozenset(sys.argv[2:])
        fmethod = lambda x: x in check
        print "Only list %s" % (", ".join(sorted(check)))
    else:
        print "Check all"
    t2s = parse_transitions(yfile)
    for trans in sorted(filter(fmethod, t2s)):
        bugs = get_bugs(t2s[trans])
        if bugs:
            print "%s: #%s" % (trans, ", #".join(str(x) for x in bugs))
        else:
            print "%s: no (open) bugs" % (trans)

