#!/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 molecular complexity."""

import os
import sys

from openeye import oechem, oemedchem


def main() -> int:
    """Sort molecules by molecular complexity."""
    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_complexity(ifs, ofs)

    return os.EX_OK


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

    complexity_list: list[tuple[float, int]] = []

    mol = oechem.OEGraphMol()
    for idx in range(mol_database.GetMaxMolIdx()):
        complex_score = float("inf")
        if mol_database.GetMolecule(mol, idx):
            oechem.OEPerceiveChiral(mol)
            complex_score = oemedchem.OETotalMolecularComplexity(mol)

        complexity_list.append((complex_score, idx))

    complexity_list.sort()

    indices = [idx for _, idx in complexity_list]

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


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