#!/usr/bin/env python3
# (C) 2026 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED.  OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.


"""Code snippet for sorting molecules by their title."""

import os
import sys

from openeye import oechem


def main() -> int:
    """Sort molecules by title."""
    if len(sys.argv) != 3:  # noqa: PLR2004
        oechem.OEThrow.Usage(f"Usage: {sys.argv[0]} <in-file> <out-file>")

    ifs = oechem.oemolistream()
    if not ifs.open(sys.argv[1]):
        oechem.OEThrow.Fatal(f"Unable to open {sys.argv[1]} for reading")

    ofs = oechem.oemolostream()
    if not ofs.open(sys.argv[2]):
        oechem.OEThrow.Fatal(f"Unable to open {sys.argv[2]} for writing")

    sort_by_title(ifs, ofs)

    return os.EX_OK


def sort_by_title(ifs: oechem.oemolistream, ofs: oechem.oemolostream) -> None:
    """Sort molecules in a database by their title and write to output."""
    mol_database = oechem.OEMolDatabase(ifs)

    titles = [(t, i) for i, t in enumerate(mol_database.GetTitles())]
    titles.sort()

    indices = [i for t, i in titles]

    mol_database.Order(indices)
    mol_database.Save(ofs)


if __name__ == "__main__":
    sys.exit(main())
