#!/usr/bin/env python3
import argparse
import re
from pathlib import Path

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('filename', type=str)
    args = parser.parse_args()
    filePath = Path(args.filename)

    with filePath.open('r') as f:
        content = f.read()

# ![](Images/image.png){#fig:fig_id width=60%}[[figure captions text.]]
# <img src="image.png" width="50%">

    # Convert custom markdown images syntax
    # ![](image.png){#fig:fig_id width=60%}[[figure captions text.]]
    # converted to
    # ![ caption ]("image.png"){width="50%"}
    content = re.sub(r'(?<!```\n)!\[.*\]\((.*)\)\{(.*)\}\s{,3}\[\[(.*?)\]\]', r'![\3](\1){\2}', content, re.DOTALL)

    # Convert custom html images syntax
    # <img src="image.png" #fig:fig_id width="50%">[[ caption ]]
    # converted to
    # ![ caption ]("image.png"){#fig:fig_id width="50%"}
    content = re.sub(r'(?<!```\n)<img\s+src=["\']([^"\']+)["\']\s*(.*)>\s{,3}\[\[(.*?)\]\]', r'![\3](\1){\2}',
                     content, re.DOTALL)

    with filePath.open('w') as f:
        f.write(content)
