import pytest
from rdkit import Chem

from macro_lactone_toolkit import MacrolactoneFragmenter
from macro_lactone_toolkit.splicing.engine import splice_molecule
from macro_lactone_toolkit.splicing.scaffold_prep import prepare_macrolactone_scaffold

from .helpers import build_macrolactone, canonicalize


def test_splice_benzene_methyl():
    scaffold = Chem.MolFromSmiles("c1ccccc1[1*]")
    fragment = Chem.MolFromSmiles("C*")

    product = splice_molecule(scaffold, fragment, position=1)

    assert canonicalize(product) == canonicalize("Cc1ccccc1")


def test_splice_missing_isotope():
    scaffold = Chem.MolFromSmiles("c1ccccc1[2*]")
    fragment = Chem.MolFromSmiles("C*")

    with pytest.raises(ValueError, match="Scaffold dummy atom with isotope 1 not found"):
        splice_molecule(scaffold, fragment, position=1)


def test_splice_no_fragment_dummy():
    scaffold = Chem.MolFromSmiles("c1ccccc1[1*]")
    fragment = Chem.MolFromSmiles("C")

    with pytest.raises(ValueError, match="Fragment does not contain a dummy atom"):
        splice_molecule(scaffold, fragment, position=1)


def test_prepare_scaffold_and_reassemble_fragment():
    built = build_macrolactone(16, {5: "ethyl"})
    result = MacrolactoneFragmenter(ring_size=16).fragment_molecule(built.smiles, parent_id="reassemble")
    fragment = next(fragment for fragment in result.fragments if fragment.cleavage_position == 5)

    scaffold, dummy_map = prepare_macrolactone_scaffold(
        built.smiles,
        positions=[5],
        ring_size=16,
    )

    assert 5 in dummy_map

    product = splice_molecule(scaffold, Chem.MolFromSmiles(fragment.fragment_smiles_labeled), position=5)

    assert canonicalize(product) == canonicalize(built.mol)
