import numpy as np
from spyrmsd import rmsd
from spyrmsd.molecule import Molecule
from rdkit import Chem
from rdkit.Chem import rdDetermineBonds
#------------------------------------------------------------------------------------------
def ase_to_spyrmsd_molecule(atoms):
    """
    Convert ASE Atoms → spyRMSD Molecule
    Detects connectivity from geometry.
    """
    symbols = atoms.get_chemical_symbols()
    coords = atoms.get_positions()
    mol = Chem.RWMol()
    for s in symbols:
        mol.AddAtom(Chem.Atom(s))
    mol = mol.GetMol()
    conf = Chem.Conformer(len(symbols))
    for i, (x, y, z) in enumerate(coords):
        conf.SetAtomPosition(i, (float(x), float(y), float(z)))
    mol.AddConformer(conf)
    rdDetermineBonds.DetermineBonds(mol)
    spy_mol = Molecule.from_rdkit(mol)
    spy_mol.coordinates = coords
    return spy_mol
#------------------------------------------------------------------------------------------
def discriminate_conformers(atomslist, rmsd_threshold=0.5):
    """
    Remove conformational duplicates while keeping structural isomers.
    Always preserves lowest-energy structure in each group.
    """
    if len(atomslist) == 0:
        return []
    atoms_sorted = sorted(atomslist, key=lambda a: a.info['e'])
    accepted = []
    accepted_spy = []
    for candidate in atoms_sorted:
        candidate_spy = ase_to_spyrmsd_molecule(candidate)
        is_duplicate = False
        for ref_spy in accepted_spy:
            if not candidate_spy.graph.is_isomorphic(ref_spy.graph):
                continue
            rmsd_value = rmsd.symmrmsd(candidate_spy, ref_spy)
            if rmsd_value < rmsd_threshold:
                is_duplicate = True
                break
        if not is_duplicate:
            accepted.append(candidate)
            accepted_spy.append(candidate_spy)
    return accepted
#------------------------------------------------------------------------------------------
