#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim: sts=4 sw=4 et
#
# Example:
# FC_DEBUG=1 firefox | ./fcdebug1.py

import sys, re
from collections import OrderedDict

quotes_re = re.compile('".*?"')

def unique(seq):
    return OrderedDict.fromkeys(seq).keys()

class hacky_str(str):
    def __init__(self, string):
        self.__lower = string.lower()
    def __hash__(self):
        return hash(self.__lower)
    def __eq__(self, other):
        return self.__lower == other.lower()
    def lower(self):
        return self.__lower

class Parser:
    def __init__(self):
        self.in_pattern = False
        self.pattern_family = None
        self.match_family = None
        self.results = {}
        self.max_pattern_len = 0

    def parse(self, line):
        if line.startswith('Match Pattern') or line.startswith('Sort Pattern'):
            self.in_pattern = True
            if self.match_family != self.pattern_family \
                    and not self.pattern_family in self.results:
                print('{} -> {}'.format(self.pattern_family, self.match_family))
                self.results[self.pattern_family] = self.match_family
            return

        if line.startswith('Pattern') or line.startswith('First font Pattern'):
            self.in_pattern = False
            return

        if line.startswith('\tfamily: '):
            if self.in_pattern:
                self.pattern_family = hacky_str(', '.join(unique([x.strip('"') for x in quotes_re.findall(line[9:])])))
                self.max_pattern_len = max(self.max_pattern_len, len(self.pattern_family))
            else:
                self.match_family = ', '.join([x.strip('"') for x in quotes_re.findall(line[9:])])


def main():
    parser = Parser()
    try:
        while True:
            line = sys.stdin.readline()
            if not line:
                break
            parser.parse(line)
    except KeyboardInterrupt:
        pass

    print(' Unique results '.center(60, '-'))
    for k, v in parser.results.items():
        print('{:{}} -> {}'.format(k, parser.max_pattern_len, v))

if __name__ == '__main__':
    main()
