from argparse import ArgumentParser
from pathlib import Path
import re
import sys

ap= ArgumentParser("add_missing_opf_finalize")
ap.add_argument("library", help="the library to fix (keep)")
ap.add_argument("tmp", help="the tmp library to use as source of OPF files")
args = ap.parse_args()

for author_folder in Path(args.library).glob("*"):
    if author_folder.is_dir():
        for title_folder in author_folder.glob("*"):
            m = re.search(r"^(.*)\((\d+)\)$", title_folder.name)
            # print (f"{title_folder}, {m.groups()}")
            if title_folder.is_dir() and m is not None:
                title = m.group(1)
                calibre_id = int(m.group(2))
                opf = title_folder / "metadata.opf"
                opf_new = title_folder / "metadata_new.opf"
                if (not opf.exists()) and opf_new.exists():
                    print (f"Renaming {opf_new} -> {opf}")
                    opf_new.rename(opf)


