#!/usr/bin/env nix-shell
#! nix-shell -i python3 --pure
#! nix-shell -p python3 python3Packages.coloredlogs

"""
Same as picture_name_date
except it's tailored for OpenCamera.
It uses filenames, that way:
- Easier to get metadata
- JPG/DNG, MP4/SRT keep the same filename
"""

import argparse
import logging
import os

import coloredlogs

log = logging.getLogger(__name__)
coloredlogs.install(level="DEBUG", fmt="%(levelname)s %(message)s", logger=log)

RAW_EXTENSIONS = [".dng"]
PRECOMP_EXTENSIONS = [".jpg", ".jpeg"]
PRECOMP_DIRECTORY = ".precomp"


def main(args: argparse.Namespace) -> None:
    for root, _, files in os.walk(args.dir):
        for filename in files:
            raw_path = os.path.join(root, filename)
            basename, raw_ext = os.path.splitext(filename)
            if raw_ext.lower() not in RAW_EXTENSIONS:
                log.debug(f"{raw_path} isn't a RAW file")
                continue

            # TODO Search for upper case extension
            for precomp_ext in PRECOMP_EXTENSIONS:
                precomp_filename = basename + precomp_ext
                precomp_path = os.path.join(root, precomp_filename)
                if not os.path.exists(precomp_path):
                    continue
                precomp_dir = os.path.join(root, PRECOMP_DIRECTORY)
                precomp_dest = os.path.join(precomp_dir, precomp_filename)
                log.info(f"{precomp_path} -> {precomp_dest} because of {raw_path}")
                if not args.dry:
                    os.makedirs(precomp_dir, exist_ok=True)
                    os.rename(precomp_path, precomp_dest)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Move pre-composed JPEG to a directory "
        "when a matching raw picture is found"
    )
    parser.add_argument(
        "dir",
        metavar="DIRECTORY",
        type=str,
        default=".",
        nargs="?",
        help="Directory containing the pictures",
    )
    parser.add_argument(
        "-d",
        "--dry",
        action="store_true",
        help="Do not actually rename, just show old and new path",
    )
    args = parser.parse_args()
    main(args)