from PyPDF2 import PdfMerger
from pathlib import Path
import re
import json


def pdf_merge(base_dir: str, report_name):
    report_prefix = re.sub(r'\[([^\]]+)\]', '', report_name)
    target = f"{base_dir}\\{report_prefix}_0.pdf"
    if Path(target).exists():
        Path(target).unlink()
    pdfs = [f for f in Path(base_dir).glob(report_prefix + '*.pdf')]
    if len(pdfs) > 0:
        with PdfMerger() as merger:
            for pdf in sorted(pdfs, key=lambda f: f.stat().st_mtime):
                merger.append(pdf)
            merger.write(target)


def get_reports(config_dir, folder):
    filename = config_dir + '\\reports.json'
    reports = json.load(open(filename, 'r'))
    return [r['name'] for r in reports if r['path'].startswith(folder)]


if __name__ == '__main__':
    reports = get_reports('C:\\GlobalCube\\Tasks\\gctools\\logs\\config', 'Team Content/ReportOutput')
    for r in reports:
        print(r)
        pdf_merge('C:\\GlobalCube\\ReportOutput\\raw', r)
