#!/usr/bin/env python

"""
Splits PFANT molecular linelist into several files, 1 file for each molecule

Output files will be named as "<original base name>-split-<molecule description>[-<n>].dat" (<n> is a number only present if
there are two or more molecules with the same description.

**Note**: existing files with same name as any output files are overwritten. This should not be a problem,
          since output filenames derive from the input filename, so there is little risk of overwritting something
          unrelated. If necessary, the input file could be isolated in a separate directory.
"""

import pyfant
import argparse
import os
import glob
import sys
import logging
import a99
import re


a99.logging_level = logging.INFO
a99.flag_log_file = False

def pprint(s):
    a99.get_python_logger().info(s)


def slugify(s):
    """Converts molecular description into something that can be used as filename.

    Steps:
        - calls a99.slugify()
        - Replaces multiple dashes with single dash
    """
    ret = a99.slugify(s)
    ret = re.sub("(-+)", "-", ret)
    return ret

def main(fn_input):
    f = pyfant.FileMolecules()
    f.load(fn_input)

    prefix = os.path.splitext(fn_input)[0]

    basenames = []
    for mol in f.molecules:
        fo = pyfant.FileMolecules()
        fo.molecules = [mol]
        fo.titm = f"Generated by split-molecules.py from '{fn_input}'"

        # Makes filename, caring for repeating descriptions
        slug = slugify(mol.description)
        _basename = basename = f"{prefix}-split-{slug}"
        n = 0
        while basename in basenames:
            n += 1
            if n > 99:
                raise RuntimeError("Too many molecules having the same description")
            basename = f"{_basename}-{n:02}"
        basenames.append(basename)

        fn_output = f"{basename}.dat"

        if os.path.isfile(fn_output):
            a99.get_python_logger().warning(f"Overwritting file '{fn_output}'")

        fo.save_as(fn_output)
        pprint(f"Saved file '{fn_output}'")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=a99.SmartFormatter)
    parser.add_argument("fn_input", type=str, help="Input filename")

    args = parser.parse_args()

    main(args.fn_input)
