"""Worked molecular examples for section 3 (ibuprofen). Writes sections/molecule_demo.json.
Usage: python -P tools/molecule_demo.py <project_dir>
Tokeniser files only are fetched from the Hugging Face hub into <project_dir>/hf (never D:).
"""
import os, sys, json, re, pathlib
root = pathlib.Path(sys.argv[1])
os.environ["HF_HOME"] = str(root / "hf")
from rdkit import Chem, rdBase, RDLogger
from rdkit.Chem import AllChem, Descriptors, Crippen, rdFingerprintGenerator, DataStructs
from transformers import AutoTokenizer
RDLogger.DisableLog("rdApp.*")

out = {"rdkit": rdBase.rdkitVersion}
smi = "CC(C)Cc1ccc(cc1)C(C)C(=O)O"          # ibuprofen, stereocentre left unspecified
m = Chem.MolFromSmiles(smi)
out["canonical"] = Chem.MolToSmiles(m)
variants = []
for i in range(m.GetNumAtoms()):
    s = Chem.MolToSmiles(m, rootedAtAtom=i, canonical=True)
    if s not in variants:
        variants.append(s)
out["n_atoms_heavy"] = m.GetNumAtoms()
out["variants_by_start_atom"] = variants
out["kekule"] = Chem.MolToSmiles(m, kekuleSmiles=True)
out["all_variants_same_canonical"] = len({Chem.MolToSmiles(Chem.MolFromSmiles(v)) for v in variants}) == 1
out["inchi"] = Chem.MolToInchi(m)
out["inchikey"] = Chem.MolToInchiKey(m)

# atom-level tokeniser: the regular expression widely used for SMILES language models
rx = r"(\[[^\]]+\]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\|\/|:|~|@|\?|>|\*|\$|\%[0-9]{2}|[0-9])"
out["atom_tokens"] = re.findall(rx, smi)
for label, name in [("gpt2", "openai-community/gpt2"), ("chemberta", "seyonec/ChemBERTa-zinc-base-v1")]:
    try:
        tok = AutoTokenizer.from_pretrained(name)
        pieces = {}
        for s in [smi, out["canonical"]]:
            ids = tok(s, add_special_tokens=False)["input_ids"]
            pieces[s] = [tok.decode([i]) for i in ids]
        out[label] = {"model": name, "pieces": pieces}
    except Exception as e:
        out[label] = {"model": name, "error": f"{type(e).__name__}: {e}"[:300]}

# Morgan fingerprint (radius 2, 2048 bits) with the substructure behind each set bit
gen = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=2048)
ao = AllChem.AdditionalOutput(); ao.AllocateBitInfoMap()
fp = gen.GetFingerprint(m, additionalOutput=ao)
bits = []
for bit, envs in sorted(ao.GetBitInfoMap().items()):
    atom, r = envs[0]
    if r == 0:
        frag = m.GetAtomWithIdx(atom).GetSymbol() + " (single atom and its bond count)"
    else:
        env = Chem.FindAtomEnvironmentOfRadiusN(m, r, atom)
        frag = Chem.MolToSmiles(Chem.PathToSubmol(m, env))
    bits.append({"bit": bit, "radius": r, "centre_atom": atom, "fragment": frag, "times": len(envs)})
out["fp_on_bits"] = bits
out["fp_n_on"] = fp.GetNumOnBits()

others = {"ibuprofen methyl ester": "CC(C)Cc1ccc(cc1)C(C)C(=O)OC",
          "flurbiprofen": "CC(C(=O)O)c1ccc(c(F)c1)-c1ccccc1",
          "naproxen": "COc1ccc2cc(ccc2c1)C(C)C(=O)O",
          "paracetamol": "CC(=O)Nc1ccc(O)cc1"}
tan = []
for name, s in others.items():
    g = gen.GetFingerprint(Chem.MolFromSmiles(s))
    a, b = set(fp.GetOnBits()), set(g.GetOnBits())
    tan.append({"other": name, "smiles": s, "on_a": len(a), "on_b": len(b), "shared": len(a & b),
                "union": len(a | b), "tanimoto": round(len(a & b) / len(a | b), 3),
                "rdkit_check": round(DataStructs.TanimotoSimilarity(fp, g), 3)})
out["tanimoto"] = tan
out["descriptors"] = {"MolWt": round(Descriptors.MolWt(m), 2), "cLogP_Crippen": round(Crippen.MolLogP(m), 2),
                      "TPSA": round(Descriptors.TPSA(m), 2), "H_bond_donors": Descriptors.NumHDonors(m),
                      "H_bond_acceptors": Descriptors.NumHAcceptors(m),
                      "rotatable_bonds": Descriptors.NumRotatableBonds(m)}
(root / "sections" / "molecule_demo.json").write_text(json.dumps(out, indent=1), encoding="utf-8")
print(json.dumps({k: v for k, v in out.items() if k != "fp_on_bits"}, indent=1))
print(len(bits), bits[:40])
