#!/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 creating a molecule database index file."""

import os
import sys
from pathlib import Path

import rich.console
from openeye import oechem


def main() -> int:
    """Create a molecule database index file."""
    if len(sys.argv) != 2:  # noqa: PLR2004
        oechem.OEThrow.Usage(f"Usage: {sys.argv[0]} <mol-file>")
        return os.EX_USAGE

    input_filename = Path(sys.argv[1])
    create_mol_database_index_file(input_filename)
    return os.EX_OK


def create_mol_database_index_file(input_filename: Path) -> None:
    """Create a molecule database index file for the given molecule file."""
    console = rich.console.Console()

    idx_filename = Path(oechem.OEGetMolDatabaseIdxFileName(str(input_filename)))

    if idx_filename.exists():
        oechem.OEThrow.Warning(f"{idx_filename} index file already exists")
    elif not oechem.OECreateMolDatabaseIdx(str(input_filename)):
        oechem.OEThrow.Warning(f"Unable to create {idx_filename} molecule index file")
    console.print(f"Index file created: {idx_filename.name}")


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