#!/usr/bin/env python3
"""
name   : rename_dwar_number_compounds.py
author : nbehrnd@yahoo.com
license: GPL v2
date   : [2024-12-18 Wed]
edit   :
purpose: edit .dwar files' filename to note the number of compounds present

A .dwar file stores the number of compound as `rowcount`; this number of lines
in the spreadsheet does not account for the table header.
"""

import argparse
import re
import shutil


def get_args():
    """Get command-line arguments"""
    parser = argparse.ArgumentParser(
        description="""
Edit .dwar filenames to indicate the number of columns present.  For instance,
file `example.dwar` is copied as `example_5_compounds.dwar`.""",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )

    parser.add_argument(
        "file",
        help="Indicate one, or (Linux:) multiple .dwar files to rename.",
        metavar="FILE",
        type=argparse.FileType("rt"),
        nargs="+",
        default=None,
    )

    parser.add_argument(
        "-v",
        "--verbose",
        help="toggle on a more verbose file processing",
        action="store_true",
    )

    return parser.parse_args()


def analyze_one_dwar_file(input_file, verbosity_level):
    """determine the number of compounds in a dwar file"""
    number_of_columns = ""
    if verbosity_level:
        print(f"work on: {input_file}")

    register = []
    try:
        with open(input_file, mode="r", encoding="utf-8") as source:
            register = source.readlines()
    except OSError as e:
        print(e)

    for line in register:
        if str("rowcount") in str(line):
            line = str(line).strip()
            number_of_compounds = int(line[11:-2])

    return number_of_compounds


def main():
    """Join the functionalities"""
    args = get_args()
    file_arg = args.file  # which is a list about one, or multiple files
    verbosity = args.verbose

    for file in file_arg:
        if str(file.name).endswith(".dwar"):
            number_of_compounds = analyze_one_dwar_file(file.name, verbosity)

            new_name = re.sub(
                ".dwar", "".join(["_", str(number_of_compounds), "_compounds.dwar"]), file.name
            )
            try:
                shutil.copyfile(file.name, new_name)
            except OSError as e:
                print(e)


if __name__ == "__main__":
    main()
