import sys
import fitz
import pprint
import collections
import json


def _round(val):
    return round(val, 3)


def _go(path):
    Artisse = collections.namedtuple('Artisse',
                                     ['name', 'surname', 'cat'])

    # open PDF
    doc = fitz.open(path)

    # find column positions
    extract = doc[0].getText('dict')
    lines = extract['blocks'][2]['lines']
    surname_x = _round(lines[0]['bbox'][0])
    name_x = _round(lines[1]['bbox'][0])
    cat_x = _round(lines[3]['bbox'][0])

    # find artisses
    infos = {}

    for page in doc:
        page_infos = {}
        infos[page.number] = page_infos
        extract = page.getText('dict')

        for block in extract['blocks']:
            if 'lines' not in block:
                continue

            name = None
            surname = None
            cat = None
            lines = block['lines']

            for line in lines:
                bbox = line['bbox']
                x = _round(bbox[0])
                y = _round(bbox[1])
                text = line['spans'][0]['text'].strip()

                if x == name_x:
                    name = text
                elif x == surname_x:
                    surname = text
                elif x == cat_x:
                    cat = text
                else:
                    continue

            if not name or not surname or not cat:
                continue

            page_infos[y] = Artisse(name, surname, cat)

    # keep unique artisses which are true members
    s = set()

    for page_infos in infos.values():
        for entry in page_infos.values():
            if entry.cat.lower().startswith('memb'):
                s.add(entry)

    # convert to array and sort by surname
    a = []

    for entry in s:
        a.append({
            'name': entry.name,
            'surname': entry.surname,
        })


    a.sort(key=lambda e: (e['surname'], e['name']))

    # output as JSON
    print(json.dumps(a, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    _go(sys.argv[1])
