import sys
import ast
from collections import Counter
conditions = map(str.strip, open('conditions.txt').readlines())



class NodeVisitor(ast.NodeVisitor):
    def __init__(self, names=None):
        self.names = [] if names is None else names
        super(NodeVisitor, self).__init__()

    def visit_Name(self, node):
        self.names.append(node.id)


def longest_prefix(s1, s2):
    for i, (a, b) in enumerate(zip(s1, s2)):
        if a != b:
            return i
    return 0


class Analyzer(object):
    ok = 0
    nok = []
    count_nodes = Counter()
    names = []


    def analyze_condition(self, condition):
        try:
            parsed = ast.parse(condition, mode='eval')
        except SyntaxError as e:
            exc_info = sys.exc_info()
            self.nok.append((condition, e.args[1][2], e))
            return
        else:
            self.ok += 1
            for node in ast.walk(parsed):
                self.count_nodes[type(node)] += 1
            visitor = NodeVisitor(self.names)
            visitor.visit(parsed)


    def analyze(self):
        for condition in conditions:
            self.analyze_condition(condition)
        print 'Bad conditions'
        for condition, offset, e in self.nok:
            print '-', condition, e
            print ' ', ' ' * (offset-1) + '^'
        print 'Node by types:'
        for node, count in sorted(self.count_nodes.iteritems(), key=lambda (x, y): -y):
            if node is ast.Load:
                continue
            print '%30s: %5d' % (node, count)
        print 'Names:', len(set(self.names))
        for name in sorted(set(self.names)):
            print '-', name



analyzer = Analyzer()
analyzer.analyze()

