#!/usr/bin/env python3
import os

from panflute import run_filter, stringify, Str, RawInline, Para, Emph, Strong, Plain, Header


def action(elem, doc):
    acros = [stringify(ac['id']) for ac in doc.metadata["acronyms"]]

    txt = stringify(elem)
    pre = ""
    pos = ""

    if len(txt) > 1 and txt not in acros:
        if not txt[0].isalnum():  # in ('(', '-'):
            pre = txt[0]
            txt = txt[1:]
        if not txt[-1].isalnum():  # in (')', ',', '.', ':', '-'):
            pos = txt[-1]
            txt = txt[:-1]

    parents = (Para, Strong, Emph, Plain, Header)
    if isinstance(elem, Str) and txt in acros and isinstance(elem.parent, parents):
        elem = RawInline(pre + "\\ac{" + txt + "}" + pos, format="latex")
        return elem


def main(doc=None):
    return run_filter(action,
                      doc=doc)


if __name__ == '__main__':
    main()
