"""Geometric neighbourhood of the distal inhibitor (ligand 892) in 1T49.

What is measured (all from deposited coordinates, chain A, asymmetric unit only):
  * heavy-atom neighbourhood of ligand 892 at a declared cutoff (4.0 A; sensitivity
    3.5/4.5/5.0 A).  This is a LIGAND NEIGHBOURHOOD, not a cavity boundary.
  * separation of the ligand from Cys215 S-gamma (both deposited SG conformers) and
    from the 176-187 loop window, with atom definitions.
  * solvent-accessible surface (Shrake-Rupley, own NumPy implementation) buried
    between ligand and protein.
  * what occupies the ligand position in 5K9W and 5K9V after the core C-alpha
    superposition (steric overlap listing).
  * local environment change of the neighbourhood residues across structures.
No pocket volume or cavity boundary is reported: no pocket-detection program was run.

Outputs: results/pocket_analysis.json, results/ligand892_neighbourhood.csv,
results/ligand892_site_occupancy.csv, results/ligand892_distances.csv
"""
import json, sys
from pathlib import Path
import numpy as np
import pandas as pd
from scipy.spatial import cKDTree

sys.path.insert(0, str(Path(__file__).resolve().parent))
import ptp1b_common as C

PRIMARY_CUTOFF = 4.0
CUTOFFS = (3.5, 4.0, 4.5, 5.0)
# Bondi van der Waals radii (A); hydrogens are absent from all three models
RADII = {"C": 1.70, "N": 1.55, "O": 1.52, "S": 1.80, "BR": 1.85, "MG": 1.73, "CL": 1.75}
PROBE = 1.4
N_SPHERE = 960


def sphere_points(n):
    i = np.arange(n) + 0.5
    phi = np.arccos(1 - 2 * i / n)
    theta = np.pi * (1 + 5 ** 0.5) * i
    return np.c_[np.cos(theta) * np.sin(phi), np.sin(theta) * np.sin(phi), np.cos(phi)]


def shrake_rupley(xyz, elements, probe=PROBE, n=N_SPHERE):
    """Per-atom SASA (A^2). Golden-spiral test points, united heavy atoms, Bondi radii."""
    xyz = np.asarray(xyz, float)
    rad = np.array([RADII[e.upper()] for e in elements]) + probe
    tree = cKDTree(xyz)
    pts = sphere_points(n)
    out = np.zeros(len(xyz))
    rmax = rad.max()
    for i in range(len(xyz)):
        nb = [j for j in tree.query_ball_point(xyz[i], rad[i] + rmax) if j != i]
        p = xyz[i] + rad[i] * pts
        ok = np.ones(n, bool)
        if nb:
            d2 = ((p[:, None, :] - xyz[nb][None, :, :]) ** 2).sum(-1)
            ok = (d2 >= (rad[nb] ** 2)[None, :]).all(1)
        out[i] = ok.mean() * 4 * np.pi * rad[i] ** 2
    return out


def main():
    T = C.load_all("highest_occupancy")
    raw1 = C.atom_table("1T49")           # keeps both Cys215 SG conformers
    t = T["1T49"]
    prot = C.protein(t).reset_index(drop=True)
    lig = t[(t["resname"] == "892")].reset_index(drop=True)
    assert len(lig) == 36 and lig["resnum"].nunique() == 1
    L = lig[["x", "y", "z"]].values
    P = prot[["x", "y", "z"]].values
    D = np.linalg.norm(P[:, None, :] - L[None, :, :], axis=-1)   # protein atoms x ligand atoms

    # ---- neighbourhood ------------------------------------------------------
    prot["dmin"] = D.min(1)
    prot["lig_atom"] = lig["atom"].values[D.argmin(1)]
    rows = []
    for (rn, name), g in prot.groupby(["resnum", "resname"]):
        if g["dmin"].min() <= max(CUTOFFS):
            k = g["dmin"].idxmin()
            rows.append(dict(resnum=int(rn), resname=name, min_heavy_atom_distance_A=float(g["dmin"].min()),
                             protein_atom=prot.loc[k, "atom"], ligand_atom=prot.loc[k, "lig_atom"],
                             n_atom_pairs_within_4A=int((D[g.index] <= PRIMARY_CUTOFF).sum()),
                             **{f"within_{c}A": bool(g["dmin"].min() <= c) for c in CUTOFFS}))
    nb = pd.DataFrame(rows).sort_values("resnum")
    helix = {r: h for h, (a, b) in {"alpha3 (188-201)": (188, 201), "alpha6 (263-282)": (263, 282)}.items() for r in range(a, b + 1)}
    nb["deposited_1T49_helix"] = nb["resnum"].map(helix).fillna("")

    # ---- SASA burial --------------------------------------------------------
    el_p, el_l = list(prot["element"]), list(lig["element"])
    sasa_complex = shrake_rupley(np.vstack([P, L]), el_p + el_l)
    sasa_prot = shrake_rupley(P, el_p)
    sasa_lig = shrake_rupley(L, el_l)
    lig_free, lig_bound = float(sasa_lig.sum()), float(sasa_complex[len(P):].sum())
    prot["dsasa"] = sasa_prot - sasa_complex[:len(P)]
    ds = prot.groupby("resnum")["dsasa"].sum()
    nb["sasa_buried_by_ligand_A2"] = nb["resnum"].map(ds).round(2)
    nb.to_csv(C.RESULTS / "ligand892_neighbourhood.csv", index=False)

    # ---- separations --------------------------------------------------------
    cen = L.mean(0)
    drows = []
    sg = raw1[(raw1["group"] == "ATOM") & (raw1["resnum"] == C.CYS215) & (raw1["atom"] == "SG")]
    for r in sg.itertuples():
        d = np.linalg.norm(L - np.array([r.x, r.y, r.z]), axis=1)
        drows.append(dict(structure="1T49", from_="ligand 892 heavy atoms (36)", to=f"Cys215 SG altloc {r.alt} (occ {r.occ:.2f})",
                          min_A=float(d.min()), closest_ligand_atom=lig["atom"][int(d.argmin())], max_A=float(d.max()),
                          centroid_A=float(np.linalg.norm(cen - np.array([r.x, r.y, r.z])))))
    def block(label, sel):
        g = prot[sel]
        d = D[g.index]
        i, j = np.unravel_index(d.argmin(), d.shape)
        gi = g.iloc[i]
        drows.append(dict(structure="1T49", from_="ligand 892 heavy atoms (36)", to=label, min_A=float(d.min()),
                          closest_ligand_atom=lig["atom"][int(j)], closest_protein_atom=f"{gi.resname}{gi.resnum} {gi.atom}",
                          max_A=float(d.max()), centroid_A=float(np.linalg.norm(cen - g[["x", "y", "z"]].values.mean(0)))))
    block("loop window 176-187, all heavy atoms", prot["resnum"].between(*C.LOOP_WINDOW))
    block("Asp181 CA", (prot["resnum"] == 181) & (prot["atom"] == "CA"))
    block("Asp181 CG", (prot["resnum"] == 181) & (prot["atom"] == "CG"))
    block("Trp179 heavy atoms", prot["resnum"] == 179)
    block("P-loop 214-221 heavy atoms", prot["resnum"].between(214, 221))
    block("Phe280 heavy atoms", prot["resnum"] == 280)
    dist = pd.DataFrame(drows).rename(columns={"from_": "from"})
    dist.to_csv(C.RESULTS / "ligand892_distances.csv", index=False)
    loop_contacts = nb[nb["resnum"].between(*C.LOOP_WINDOW)]
    near_loop = nb[nb["resnum"].between(C.LOOP_WINDOW[0], 200)]

    # ---- what sits at the ligand position in the other two structures --------
    occ_rows, occ_summary = [], {}
    lig_in = {}
    for other in ("5K9W", "5K9V"):
        R, tv, fit, res = C.core_transform(T, "1T49", other, False)
        Lo = C.apply(R, tv, L)
        lig_in[other] = Lo
        po = C.protein(T[other]).reset_index(drop=True)
        Do = np.linalg.norm(po[["x", "y", "z"]].values[:, None, :] - Lo[None, :, :], axis=-1)
        po["dmin"] = Do.min(1)
        po["lig_atom"] = lig["atom"].values[Do.argmin(1)]
        summ = {f"n_protein_heavy_atoms_within_{c}A_of_superposed_ligand": int((po["dmin"] <= c).sum()) for c in (2.0, 2.5, 3.0, 4.0)}
        summ["n_ligand_atoms_with_protein_atom_within_2.5A"] = int((Do.min(0) <= 2.5).sum())
        summ["fit_rmsd_A"] = fit
        occ_summary[other] = summ
        for (rn, name), g in po.groupby(["resnum", "resname"]):
            if g["dmin"].min() <= 4.0:
                k = g["dmin"].idxmin()
                occ_rows.append(dict(structure=other, resnum=int(rn), resname=name, min_distance_to_superposed_ligand_A=float(g["dmin"].min()),
                                     protein_atom=po.loc[k, "atom"], ligand_atom=po.loc[k, "lig_atom"],
                                     n_atoms_within_2p5A=int((g["dmin"] <= 2.5).sum()),
                                     in_1T49_neighbourhood_4A=bool(rn in set(nb[nb["within_4.0A"]]["resnum"])),
                                     modelled_in_1T49=bool(rn in set(prot["resnum"]))))
    occ = pd.DataFrame(occ_rows).sort_values(["structure", "min_distance_to_superposed_ligand_A"])
    occ.to_csv(C.RESULTS / "ligand892_site_occupancy.csv", index=False)

    # ---- local environment change of neighbourhood residues -------------------
    env = []
    site = list(nb[nb["within_4.0A"]]["resnum"])
    for other in ("5K9V", "5K9W"):
        R, tv, fit, res = C.core_transform(T, "1T49", other, False)
        po = C.protein(T[other])
        for rn in site:
            a = prot[prot["resnum"] == rn].set_index("atom")[["x", "y", "z"]]
            b = po[po["resnum"] == rn].set_index("atom")[["x", "y", "z"]]
            if len(b) == 0:   # residue not modelled in the other structure: no comparison is possible
                env.append(dict(compared_with=other, resnum=int(rn), resname=prot[prot["resnum"] == rn]["resname"].iloc[0],
                                n_matched_heavy_atoms=0, n_atoms_1T49=len(a), n_atoms_other=0,
                                CA_displacement_A=np.nan, all_heavy_atom_rmsd_A=np.nan, side_chain_rmsd_A=np.nan))
                continue
            idx = a.index.intersection(b.index)
            sc =[x for x in idx if x not in C.BACKBONE]
            A = C.apply(R, tv, a.loc[idx].values)
            env.append(dict(compared_with=other, resnum=int(rn), resname=prot[prot["resnum"] == rn]["resname"].iloc[0],
                            n_matched_heavy_atoms=len(idx), n_atoms_1T49=len(a), n_atoms_other=len(b),
                            CA_displacement_A=float(np.linalg.norm(C.apply(R, tv, a.loc["CA"].values) - b.loc["CA"].values)),
                            all_heavy_atom_rmsd_A=C.rmsd(A, b.loc[idx].values),
                            side_chain_rmsd_A=(C.rmsd(C.apply(R, tv, a.loc[sc].values), b.loc[sc].values) if sc else np.nan)))
    env = pd.DataFrame(env)
    env.to_csv(C.RESULTS / "ligand892_site_environment_change.csv", index=False)

    # ---- ligand van der Waals union volume (ligand, NOT pocket) ---------------
    h = 0.2
    lo, hi = L.min(0) - 2.5, L.max(0) + 2.5
    gx = np.mgrid[lo[0]:hi[0]:h, lo[1]:hi[1]:h, lo[2]:hi[2]:h].reshape(3, -1).T
    rl = np.array([RADII[e.upper()] for e in el_l])
    inside = np.zeros(len(gx), bool)
    for c, r in zip(L, rl):
        inside |= ((gx - c) ** 2).sum(1) <= r * r
    lig_vol = float(inside.sum() * h ** 3)

    out = dict(
        structure="1T49", chain="A", ligand=dict(comp_id="892", auth_seq_id=int(lig["resnum"].iloc[0]), n_heavy_atoms=36,
                                                 elements=lig["element"].value_counts().to_dict(),
                                                 mean_B_A2=float(lig["b"].mean()), occupancy=sorted(set(lig["occ"])),
                                                 centroid_xyz_deposited_frame=cen.round(3).tolist()),
        definition="Ligand neighbourhood = protein residues (chain A, asymmetric unit, one conformer per residue) with any heavy atom "
                   f"within {PRIMARY_CUTOFF} A of any ligand-892 heavy atom. This is not a cavity boundary and no pocket volume is reported.",
        primary_cutoff_A=PRIMARY_CUTOFF,
        neighbourhood_residues={f"{c}A": [f"{r.resname}{r.resnum}" for r in nb[nb[f'within_{c}A']].itertuples()] for c in CUTOFFS},
        n_neighbourhood_residues={f"{c}A": int(nb[f"within_{c}A"].sum()) for c in CUTOFFS},
        n_atom_pairs_within_4A=int((D <= PRIMARY_CUTOFF).sum()),
        waters_within_4A=int((np.linalg.norm(t[t["resname"] == "HOH"][["x", "y", "z"]].values[:, None, :] - L[None], axis=-1).min(1) <= 4.0).sum()),
        sasa=dict(method=f"Shrake-Rupley, {N_SPHERE} points/atom, probe {PROBE} A, Bondi radii, heavy atoms only, waters and Mg excluded",
                  ligand_free_A2=lig_free, ligand_in_complex_A2=lig_bound, ligand_buried_A2=lig_free - lig_bound,
                  ligand_fraction_buried=(lig_free - lig_bound) / lig_free,
                  protein_buried_by_ligand_A2=float(prot["dsasa"].sum())),
        ligand_vdw_union_volume_A3=dict(value=lig_vol, note="volume of the ligand's own Bondi-sphere union on a 0.2 A grid; a ligand size, not a pocket volume"),
        separation_from_catalytic_site=dist.to_dict(orient="records"),
        loop_window_contacts=dict(residues_176_187_within_4A=[f"{r.resname}{r.resnum}" for r in loop_contacts[loop_contacts["within_4.0A"]].itertuples()],
                                  residues_176_187_within_5A=[f"{r.resname}{r.resnum}" for r in loop_contacts[loop_contacts["within_5.0A"]].itertuples()],
                                  neighbourhood_residues_176_200_within_5A=[dict(res=f"{r.resname}{r.resnum}", min_A=round(r.min_heavy_atom_distance_A, 3),
                                                                                protein_atom=r.protein_atom, ligand_atom=r.ligand_atom) for r in near_loop.itertuples()]),
        site_occupancy_in_other_structures=dict(
            method="ligand 892 coordinates rigidly transformed with the 1T49->target core C-alpha fit; protein heavy atoms of the target within the stated distance",
            summary=occ_summary,
            closest_residues={o: [dict(res=f"{r.resname}{r.resnum}", min_A=round(r.min_distance_to_superposed_ligand_A, 3), atoms_within_2p5A=int(r.n_atoms_within_2p5A),
                                       modelled_in_1T49=r.modelled_in_1T49) for r in occ[(occ.structure == o) & (occ.min_distance_to_superposed_ligand_A <= 3.0)].itertuples()]
                              for o in ("5K9W", "5K9V")}),
        limitations=["Asymmetric unit only: symmetry-related molecules were not generated, so crystal-packing contacts of the ligand are not assessed.",
                     "Hydrogens absent; distances are heavy-atom distances.",
                     "1T49 residues 283-298 are not modelled, so any ligand contacts with the C-terminal segment in solution are unobservable here.",
                     "No cavity detection program (fpocket/CASTp etc.) was available; no pocket volume or boundary is claimed."],
        source_files=["data/raw/1T49.cif", "data/raw/5K9W.cif", "data/raw/5K9V.cif"],
        tables=["results/ligand892_neighbourhood.csv", "results/ligand892_distances.csv", "results/ligand892_site_occupancy.csv",
                "results/ligand892_site_environment_change.csv"],
    )
    (C.RESULTS / "pocket_analysis.json").write_text(json.dumps(out, indent=2, default=float))
    pd.set_option("display.width", 250, "display.max_columns", 30)
    print(nb.round(3).to_string(index=False))
    print(dist.round(3).to_string(index=False))
    print(json.dumps(out["sasa"], indent=1, default=float)); print("ligand vdW volume", round(lig_vol, 1))
    print(json.dumps(occ_summary, indent=1))
    print(occ[occ.min_distance_to_superposed_ligand_A <= 3.2].round(3).to_string(index=False))
    print(env.round(3).to_string(index=False))


if __name__ == "__main__":
    main()
