#!/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 counting molecules in input files."""

import os
import sys
from pathlib import Path

from openeye import oechem
from rich.console import Console


def main() -> int:
    """Count molecules in input files."""
    if len(sys.argv) < 2:  # noqa: PLR2004
        oechem.OEThrow.Usage(f"Usage: {sys.argv[0]} <mol-file> ...")

    console = Console()

    total_mols = 0
    for fname in sys.argv[1:]:
        total_mols += mol_count(Path(fname), console)
    console.print("===========================================================")
    console.print(f"Total {total_mols} molecules")

    return os.EX_OK


def mol_count(fname: Path, console: Console) -> int:
    """Count the number of molecules in a file."""
    ifs = oechem.oemolistream()
    if not ifs.open(str(fname)):
        oechem.OEThrow.Warning(f"Unable to open {fname.name} for reading")
        return 0

    mol_database = oechem.OEMolDatabase(ifs)
    num_mols = mol_database.NumMols()
    console.print(f"{fname.name} contains {num_mols} molecule(s).")
    return num_mols


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