"""Follow-up controls added in response to the review round (provenance/llm_review_round1.json).

  a. ligand 892 distance to residues 176-186 separately from Ser187
  b. supplementary apo entry 1SUG put through the same core fit / loop analysis,
     and active-site contents of every entry (non-protein atoms near Cys215 SG)
  c. loop-window order: alternate conformers, occupancies and B-factors
  d. contact-cutoff sensitivity of the loop-window contact differences
  e. local (alpha3 + alpha6) superposition for the transplanted-ligand overlap
  f. crystal-lattice contacts: symmetry mates generated from the REMARK 290 operators
     and CRYST1 cell of the legacy PDB files (core three entries)

Outputs: results/review_followup.json, results/crystal_contacts.csv,
         results/loop_order_metrics.csv, results/sug_control.csv
"""
import json, sys, itertools
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
from Bio.PDB.MMCIF2Dict import MMCIF2Dict


def load_extra(path):
    d = MMCIF2Dict(str(path))
    a = pd.DataFrame({k.split(".")[1]: d[k] for k in d if k.startswith("_atom_site.")})
    t = pd.DataFrame({"group": a["group_PDB"], "chain": a["auth_asym_id"], "resnum": a["auth_seq_id"].astype(int), "label_seq": 0,
                      "resname": a["auth_comp_id"], "atom": a["label_atom_id"].str.strip('"'), "alt": a["label_alt_id"],
                      "occ": a["occupancy"].astype(float), "b": a["B_iso_or_equiv"].astype(float), "x": a["Cartn_x"].astype(float),
                      "y": a["Cartn_y"].astype(float), "z": a["Cartn_z"].astype(float), "element": a["type_symbol"]})
    return t, d


def symmetry_mates(pid):
    """Symmetry-related copies of chain A heavy atoms (no waters) from the legacy PDB header."""
    ops, cell = {}, None
    for line in (C.RAW / f"{pid}.pdb").read_text().splitlines():
        if line.startswith("REMARK 290   SMTRY"):
            f = line.split()
            ops.setdefault(int(f[3]), {})[int(f[2][-1])] = [float(x) for x in f[4:8]]
        elif line.startswith("CRYST1"):
            cell = [float(line[6:15]), float(line[15:24]), float(line[24:33]), float(line[33:40]), float(line[40:47]), float(line[47:54])]
    a, b, c, al, be, ga = cell
    al, be, ga = np.radians([al, be, ga])
    va = np.array([a, 0, 0])
    vb = np.array([b * np.cos(ga), b * np.sin(ga), 0])
    cx = c * np.cos(be)
    cy = c * (np.cos(al) - np.cos(be) * np.cos(ga)) / np.sin(ga)
    vc = np.array([cx, cy, np.sqrt(c * c - cx * cx - cy * cy)])
    t = C.select_altloc(C.atom_table(pid))
    t = t[(t["chain"] == C.CHAIN) & (t["resname"] != "HOH")].reset_index(drop=True)
    xyz = t[["x", "y", "z"]].values
    centre, radius = xyz.mean(0), np.linalg.norm(xyz - xyz.mean(0), axis=1).max()
    mates = []
    for k, op in sorted(ops.items()):
        M = np.array([op[1], op[2], op[3]])
        R, tr = M[:, :3], M[:, 3]
        base = xyz @ R.T + tr
        for i, j, l in itertools.product(range(-3, 4), repeat=3):
            if k == 1 and (i, j, l) == (0, 0, 0):
                continue
            shift = i * va + j * vb + l * vc
            if np.linalg.norm(base.mean(0) + shift - centre) > 2 * radius + 6:
                continue
            m = t[["resnum", "resname", "atom", "group"]].copy()
            m[["x", "y", "z"]] = base + shift
            m["operator"] = f"op{k} cell({i},{j},{l})"
            mates.append(m)
    return t, pd.concat(mates, ignore_index=True), dict(n_operators=len(ops), cell=cell, n_mate_copies_considered=len(mates))


def main():
    T = C.load_all("highest_occupancy")
    out = {}

    # ---- a. ligand to 176-186 vs Ser187 -------------------------------------------------
    t = T["1T49"]
    lig = t[t["resname"] == "892"][["x", "y", "z"]].values
    p = C.protein(t)
    def mind(sel):
        g = p[sel]
        D = np.linalg.norm(g[["x", "y", "z"]].values[:, None] - lig[None], axis=-1)
        i = np.unravel_index(D.argmin(), D.shape)[0]
        return dict(min_A=float(D.min()), protein_atom=f"{g.iloc[i].resname}{g.iloc[i].resnum} {g.iloc[i].atom}")
    out["a_ligand892_to_loop"] = dict(residues_176_186=mind(p["resnum"].between(176, 186)), Ser187=mind(p["resnum"] == 187),
                                      WPD_tripeptide_179_181=mind(p["resnum"].between(179, 181)),
                                      n_loop_window_atoms_within_4A=int((np.linalg.norm(p[p["resnum"].between(176, 187)][["x", "y", "z"]].values[:, None] - lig[None], axis=-1).min(1) <= 4.0).sum()),
                                      n_loop_window_atoms_within_5A=int((np.linalg.norm(p[p["resnum"].between(176, 187)][["x", "y", "z"]].values[:, None] - lig[None], axis=-1).min(1) <= 5.0).sum()))

    # ---- b. 1SUG control and active-site contents ------------------------------------------
    S = dict(T)
    extra = C.ROOT / "sources" / "case" / "1SUG.cif"
    sug_meta = None
    if extra.exists():
        raw, d = load_extra(extra)
        S["1SUG"] = C.select_altloc(raw)
        ps = C.protein(S["1SUG"])
        sug_meta = dict(title=d["_struct.title"][0], resolution_A=float(d["_refine.ls_d_res_high"][0]), space_group=d["_symmetry.space_group_name_H-M"][0],
                        modelled_range=[int(ps["resnum"].min()), int(ps["resnum"].max())],
                        source="sources/case/1SUG.cif (retrieved by the independent technician; SHA-256 in sources/case/retrieval.json)")
    rows = []
    lo, hi = C.COMPARE_RANGE
    loop = list(range(C.LOOP_WINDOW[0], C.LOOP_WINDOW[1] + 1))
    if "1SUG" in S:
        cs = C.ca_coords(S["1SUG"])
        for ref in C.IDS:
            cr = C.ca_coords(T[ref])
            res = [r for r in C.fit_residue_set(False) if r in cs]
            assert all(cs[r][0] == cr[r][0] for r in res)
            R, tv, fit = C.kabsch(np.array([cs[r][1] for r in res]), np.array([cr[r][1] for r in res]))
            disp = {r: float(np.linalg.norm(C.apply(R, tv, cs[r][1]) - cr[r][1])) for r in range(lo, hi + 1) if r in cs}
            rows.append(dict(mobile="1SUG", reference=ref, n_fit_CA=len(res), fit_rmsd_A=fit,
                             rmsd_all_CA_2_280_A=float(np.sqrt(np.mean([v * v for v in disp.values()]))),
                             loop_176_187_rmsd_fitted_frame_A=float(np.sqrt(np.mean([disp[r] ** 2 for r in loop]))),
                             asp181_CA_displacement_A=disp[181], lys239_CA_displacement_A=disp[239]))
    sug = pd.DataFrame(rows)
    sug.to_csv(C.RESULTS / "sug_control.csv", index=False)
    site = {}
    for pid, tt in S.items():
        tt = tt[tt["chain"] == C.CHAIN]
        sg = tt[(tt["group"] == "ATOM") & (tt["resnum"] == 215) & (tt["atom"] == "SG")][["x", "y", "z"]].values[0]
        het = tt[tt["group"] == "HETATM"].copy()
        het["d"] = np.linalg.norm(het[["x", "y", "z"]].values - sg, axis=1)
        near = het[het["d"] <= 8.0]
        nonwater = near[near["resname"] != "HOH"]
        site[pid] = dict(non_water_hetero_groups_within_8A_of_Cys215_SG=sorted(f"{r}{n}" for r, n in set(zip(nonwater["resname"], nonwater["resnum"]))),
                         closest_non_water_hetero_atom_A=(float(nonwater["d"].min()) if len(nonwater) else None),
                         n_waters_within_8A=int((near["resname"] == "HOH").sum()))
    out["b_1SUG_control"] = dict(metadata=sug_meta, same_core_fit=sug.round(4).to_dict(orient="records"), active_site_contents=site)

    # ---- c. loop order --------------------------------------------------------------------
    rows = []
    for pid in C.IDS:
        rawp = C.protein(C.atom_table(pid))
        ca = rawp[rawp["atom"] == "CA"]
        for name, (a, b) in {"loop window 176-187": (176, 187), "residues 237-243": (237, 243), "common range 2-280": (2, 280),
                             "alpha7 285-296": (285, 296)}.items():
            g, gc = rawp[rawp["resnum"].between(a, b)], ca[ca["resnum"].between(a, b)]
            rows.append(dict(structure=pid, region=name, n_residues_modelled=int(g["resnum"].nunique()),
                             n_atoms_with_altloc=int((g["alt"] != ".").sum()), min_occupancy=(float(g["occ"].min()) if len(g) else np.nan),
                             mean_CA_B_A2=(float(gc["b"].mean()) if len(gc) else np.nan), max_CA_B_A2=(float(gc["b"].max()) if len(gc) else np.nan)))
    order = pd.DataFrame(rows)
    ref = order[order.region == "common range 2-280"].set_index("structure")["mean_CA_B_A2"]
    order["mean_CA_B_relative_to_2_280"] = order["mean_CA_B_A2"] / order["structure"].map(ref)
    order.to_csv(C.RESULTS / "loop_order_metrics.csv", index=False)
    out["c_loop_order"] = order.round(3).to_dict(orient="records")

    # ---- d. contact cutoff sensitivity -------------------------------------------------------
    diff = pd.read_csv(C.RESULTS / "contact_differences.csv")
    key = diff[diff["robust_gt_1A"] & diff["involves_loop_window"]]
    sens = {}
    for cut in (3.5, 4.0, 4.5):
        st = {pid: key[f"min_dist_{pid}_A"] <= cut for pid in C.IDS}
        sens[f"{cut}A"] = dict(n_pairs_5K9W_differs_from_both_others=int(((st["5K9W"] != st["5K9V"]) & (st["5K9W"] != st["1T49"])).sum()),
                               n_pairs_5K9V_and_1T49_agree=int((st["5K9V"] == st["1T49"]).sum()), n_pairs=int(len(key)))
    out["d_contact_cutoff_sensitivity"] = sens

    # ---- e. local superposition for the ligand overlap -------------------------------------------
    local = [r for r in list(range(188, 202)) + list(range(263, 281))]
    res = {}
    for other in ("5K9W", "5K9V"):
        cm, cr = C.ca_coords(T["1T49"]), C.ca_coords(T[other])
        R, tv, fit = C.kabsch(np.array([cm[r][1] for r in local]), np.array([cr[r][1] for r in local]))
        L = C.apply(R, tv, lig)
        po = C.protein(T[other]).reset_index(drop=True)
        D = np.linalg.norm(po[["x", "y", "z"]].values[:, None] - L[None], axis=-1).min(1)
        po["d"] = D
        per = po.groupby(["resnum", "resname"])["d"].min().sort_values().head(6)
        res[other] = dict(n_fit_CA=len(local), local_fit_rmsd_A=fit, n_protein_heavy_atoms_within_2A=int((D <= 2.0).sum()),
                          closest_residues=[dict(res=f"{n}{r}", min_A=round(float(v), 3)) for (r, n), v in per.items()])
    out["e_local_alpha3_alpha6_fit_overlap"] = res

    # ---- f. crystal-lattice contacts ------------------------------------------------------------
    rows, summary = [], {}
    groups = {"loop window 176-187": lambda t: (t["group"] == "ATOM") & t["resnum"].between(176, 187),
              "WPD 179-182": lambda t: (t["group"] == "ATOM") & t["resnum"].between(179, 182),
              "residues 237-243": lambda t: (t["group"] == "ATOM") & t["resnum"].between(237, 243),
              "alpha7 285-297": lambda t: (t["group"] == "ATOM") & t["resnum"].between(285, 297),
              "ligand-892 site residues (4 A set)": lambda t: (t["group"] == "ATOM") & t["resnum"].isin([189, 192, 193, 196, 197, 200, 276, 277, 279, 280, 281, 282]),
              "ligand 892": lambda t: t["resname"] == "892",
              "TCS401 (OTA)": lambda t: t["resname"] == "OTA"}
    for pid in C.IDS:
        asu, mates, info = symmetry_mates(pid)
        tree = cKDTree(mates[["x", "y", "z"]].values)
        # sanity: nothing should overlap the asymmetric unit
        dmin_all = tree.query(asu[["x", "y", "z"]].values)[0].min()
        summary[pid] = dict(info, closest_symmetry_mate_atom_to_asymmetric_unit_A=float(dmin_all))
        for name, sel in groups.items():
            g = asu[sel(asu)]
            if len(g) == 0:
                rows.append(dict(structure=pid, group=name, status="not modelled / not present", n_group_atoms=0))
                continue
            d, idx = tree.query(g[["x", "y", "z"]].values)
            near = tree.query_ball_point(g[["x", "y", "z"]].values, 4.0)
            hit = sorted({j for lst in near for j in lst})
            m = mates.iloc[hit]
            k = int(d.argmin())
            rows.append(dict(structure=pid, group=name, status="measured", n_group_atoms=int(len(g)),
                             min_distance_to_symmetry_mate_A=float(d.min()),
                             closest_pair=f"{g.iloc[k].resname}{g.iloc[k].resnum} {g.iloc[k].atom} ... {mates.iloc[idx[k]].resname}{mates.iloc[idx[k]].resnum} {mates.iloc[idx[k]].atom} [{mates.iloc[idx[k]].operator}]",
                             n_group_atoms_within_4A_of_mate=int((d <= 4.0).sum()), n_mate_atoms_within_4A=int(len(m)),
                             group_residues_in_contact=" ".join(str(r) for r in sorted(set(g[d <= 4.0]["resnum"]))),
                             mate_residues_in_contact=" ".join(sorted({f"{a}{b}" for a, b in zip(m["resname"], m["resnum"])}, key=lambda s: int("".join(ch for ch in s[3:] if ch.isdigit() or ch == "-") or 0)))))
    cc = pd.DataFrame(rows)
    cc.to_csv(C.RESULTS / "crystal_contacts.csv", index=False)
    out["f_crystal_contacts"] = dict(method="symmetry operators from REMARK 290 (orthogonal frame) plus lattice translations -3..3 built from CRYST1; chain A heavy atoms, "
                                            "waters excluded; contact = any symmetry-mate atom within 4.0 A", per_structure=summary,
                                     table="results/crystal_contacts.csv")
    # ---- g. would an open loop fit in the closed-state (5K9W) lattice? ----------------------------
    # The open-loop coordinates of 5K9V / 1T49 are carried into the 5K9W frame with the core fit and
    # compared with the symmetry mates of 5K9W. This asks only whether the two models are
    # geometrically compatible in that lattice; it is not a statement about solution behaviour.
    asu, mates, _ = symmetry_mates("5K9W")
    tree = cKDTree(mates[["x", "y", "z"]].values)
    g_rows = {}
    for src in ("5K9W", "5K9V", "1T49"):
        ps = C.protein(T[src])
        lp = ps[ps["resnum"].between(176, 187)].reset_index(drop=True)
        xyz = lp[["x", "y", "z"]].values
        if src != "5K9W":
            R, tv, _, _ = C.core_transform(T, src, "5K9W", False)
            xyz = C.apply(R, tv, xyz)
        d, idx = tree.query(xyz)
        k = int(d.argmin())
        hit = mates.iloc[sorted({j for lst in tree.query_ball_point(xyz, 3.0) for j in lst})]
        g_rows[src] = dict(min_distance_to_5K9W_symmetry_mate_A=float(d.min()),
                           closest_pair=f"{lp.iloc[k].resname}{lp.iloc[k].resnum} {lp.iloc[k].atom} ... {mates.iloc[idx[k]].resname}{mates.iloc[idx[k]].resnum} {mates.iloc[idx[k]].atom}",
                           n_loop_atoms_within_3A=int((d <= 3.0).sum()), n_loop_atoms_within_2p2A=int((d <= 2.2).sum()),
                           loop_residues_within_3A=sorted(int(r) for r in set(lp[d <= 3.0]["resnum"])),
                           mate_residues_within_3A=sorted({f"{a}{b}" for a, b in zip(hit["resname"], hit["resnum"])}))
    out["g_open_loop_in_5K9W_lattice"] = dict(
        method="loop-window atoms (176-187) of each entry in the 5K9W frame (core C-alpha fit) vs symmetry mates of 5K9W", per_loop_source=g_rows)
    print(json.dumps(g_rows, indent=1))
    (C.RESULTS / "review_followup.json").write_text(json.dumps(out, indent=1, default=float))
    pd.set_option("display.width", 260, "display.max_columns", 30, "display.max_colwidth", 70)
    print(json.dumps(out["a_ligand892_to_loop"], indent=1))
    print(sug.round(3).to_string(index=False)); print(json.dumps(site, indent=1)); print(sug_meta)
    print(order.round(2).to_string(index=False))
    print(json.dumps(sens)); print(json.dumps(res, indent=1)); print(json.dumps(summary))
    print(cc[["structure", "group", "status", "min_distance_to_symmetry_mate_A", "n_group_atoms_within_4A_of_mate", "group_residues_in_contact", "mate_residues_in_contact"]].round(2).to_string(index=False))


if __name__ == "__main__":
    main()
