"""Residue contact maps and selected inter-region distances for 5K9W, 5K9V, 1T49.

Contact definition (declared): two protein residues of chain A (asymmetric unit,
one conformer per residue, heavy atoms only) are in contact when their minimum
heavy-atom distance is <= 4.0 A and their sequence separation is >= 3.

Outputs:
  results/contact_maps.csv          long table, one row per structure x residue pair
  results/contact_differences.csv   pairs within the common 2-280 range whose contact
                                    state differs between structures
  results/loop_contact_summary.csv  contacts of each 176-187 residue per structure
  results/region_distances.csv      declared atom-atom / group distances per structure
"""
import 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

CONTACT_CUTOFF = 4.0
MIN_SEQ_SEP = 3
REGIONS = {  # residue ranges used only as labels in the tables
    "WPD-loop window (176-187)": (176, 187),
    "P-loop (214-221)": (214, 221),
    "alpha3 (188-201)": (188, 201),
    "alpha6 (263-282)": (263, 282),
    "alpha7 (285-296, 5K9W deposited helix)": (285, 296),
}


def region_of(r):
    for name, (a, b) in REGIONS.items():
        if a <= r <= b:
            return name
    return ""


def contacts(t):
    p = C.protein(t).reset_index(drop=True)
    xyz = p[["x", "y", "z"]].values
    pairs = cKDTree(xyz).query_pairs(CONTACT_CUTOFF, output_type="ndarray")
    d = np.linalg.norm(xyz[pairs[:, 0]] - xyz[pairs[:, 1]], axis=1)
    df = pd.DataFrame({"i": p["resnum"].values[pairs[:, 0]], "j": p["resnum"].values[pairs[:, 1]], "d": d,
                       "ai": p["atom"].values[pairs[:, 0]], "aj": p["atom"].values[pairs[:, 1]]})
    sw = df["i"] > df["j"]
    df.loc[sw, ["i", "j", "ai", "aj"]] = df.loc[sw, ["j", "i", "aj", "ai"]].values
    df = df[(df["j"] - df["i"]) >= MIN_SEQ_SEP]
    g = df.sort_values("d").groupby(["i", "j"])
    out = g.first().rename(columns={"d": "min_heavy_atom_distance_A", "ai": "atom_i", "aj": "atom_j"})
    out["n_atom_pairs_within_cutoff"] = g.size()
    names = p.drop_duplicates("resnum").set_index("resnum")["resname"]
    out = out.reset_index().rename(columns={"i": "res_i", "j": "res_j"})
    out["resname_i"] = out["res_i"].map(names)
    out["resname_j"] = out["res_j"].map(names)
    return out


def min_dist(t, sel_a, sel_b):
    p = C.protein(t)
    a, b = p[sel_a(p)], p[sel_b(p)]
    if len(a) == 0 or len(b) == 0:
        return np.nan, "", ""
    D = np.linalg.norm(a[["x", "y", "z"]].values[:, None] - b[["x", "y", "z"]].values[None], axis=-1)
    i, j = np.unravel_index(D.argmin(), D.shape)
    return float(D.min()), f"{a.iloc[i].resname}{a.iloc[i].resnum} {a.iloc[i].atom}", f"{b.iloc[j].resname}{b.iloc[j].resnum} {b.iloc[j].atom}"


def atom(res, name):
    return lambda p: (p["resnum"] == res) & (p["atom"] == name)


def res(a, b=None):
    b = a if b is None else b
    return lambda p: p["resnum"].between(a, b)


def sidechain(r):
    return lambda p: (p["resnum"] == r) & (~p["atom"].isin(C.BACKBONE))


DISTANCES = [  # (label, selection A, selection B, kind)
    ("Asp181 CA - Cys215 CA", atom(181, "CA"), atom(215, "CA"), "atom-atom"),
    ("Asp181 CG - Cys215 SG", atom(181, "CG"), atom(215, "SG"), "atom-atom"),
    ("Phe182 CZ - Cys215 SG", atom(182, "CZ"), atom(215, "SG"), "atom-atom"),
    ("Trp179 NE1 - Arg221 (min, any heavy atom)", atom(179, "NE1"), res(221), "atom-group min"),
    ("Trp179 side chain - Phe269 side chain (min)", sidechain(179), sidechain(269), "group min"),
    ("loop window 176-187 - P-loop 214-221 (min heavy atom)", res(176, 187), res(214, 221), "group min"),
    ("loop window 176-187 - alpha3 189-201 (min heavy atom)", res(176, 187), res(189, 201), "group min"),
    ("loop window 176-187 - alpha6 264-280 (min heavy atom)", res(176, 187), res(264, 280), "group min"),
    ("loop window 176-187 - alpha7 285-296 (min heavy atom)", res(176, 187), res(285, 296), "group min"),
    ("alpha3 189-201 - alpha7 285-296 (min heavy atom)", res(189, 201), res(285, 296), "group min"),
    ("alpha6 264-280 - alpha7 285-296 (min heavy atom)", res(264, 280), res(285, 296), "group min"),
    ("Tyr152 OH - Asn193 (min heavy atom)", atom(152, "OH"), res(193), "atom-group min"),
    ("Asn193 side chain - Trp291 side chain (min)", sidechain(193), sidechain(291), "group min"),
    ("Phe196 side chain - Phe280 side chain (min)", sidechain(196), sidechain(280), "group min"),
    ("Leu192 side chain - Phe280 side chain (min)", sidechain(192), sidechain(280), "group min"),
    ("Phe191 side chain - Trp179 side chain (min)", sidechain(191), sidechain(179), "group min"),
]


def main():
    T = C.load_all("highest_occupancy")
    extra = C.ROOT / "sources" / "case" / "1SUG.cif"   # supplementary apo control, if present
    maps = []
    for pid in C.IDS:
        c = contacts(T[pid])
        c.insert(0, "structure", pid)
        maps.append(c)
    cm = pd.concat(maps, ignore_index=True)
    cm["region_i"] = cm["res_i"].map(region_of)
    cm["region_j"] = cm["res_j"].map(region_of)
    lo, hi = C.COMPARE_RANGE
    cm["both_in_common_range_2_280"] = cm["res_i"].between(lo, hi) & cm["res_j"].between(lo, hi)
    cm["involves_loop_window"] = cm["res_i"].between(*C.LOOP_WINDOW) | cm["res_j"].between(*C.LOOP_WINDOW)
    cm = cm[["structure", "res_i", "resname_i", "res_j", "resname_j", "min_heavy_atom_distance_A", "atom_i", "atom_j",
             "n_atom_pairs_within_cutoff", "region_i", "region_j", "both_in_common_range_2_280", "involves_loop_window"]]
    cm.to_csv(C.RESULTS / "contact_maps.csv", index=False)

    # ---- differences within the common range --------------------------------
    common = cm[cm["both_in_common_range_2_280"]]
    wide = common.pivot_table(index=["res_i", "resname_i", "res_j", "resname_j"], columns="structure",
                              values="min_heavy_atom_distance_A").reindex(columns=list(C.IDS))
    # for pairs lacking a contact in a structure, fill in the actual minimum distance
    P = {pid: C.protein(T[pid]) for pid in C.IDS}
    coords = {pid: {r: g[["x", "y", "z"]].values for r, g in P[pid].groupby("resnum")} for pid in C.IDS}
    def full(pid, i, j):
        a, b = coords[pid][i], coords[pid][j]
        return float(np.linalg.norm(a[:, None] - b[None], axis=-1).min())
    wide = wide.reset_index()
    for pid in C.IDS:
        wide[f"contact_{pid}"] = wide[pid].notna()
        wide[f"min_dist_{pid}_A"] = [full(pid, i, j) for i, j in zip(wide["res_i"], wide["res_j"])]
    wide = wide.drop(columns=list(C.IDS))
    wide["n_structures_in_contact"] = wide[[f"contact_{p}" for p in C.IDS]].sum(1)
    wide["involves_loop_window"] = wide["res_i"].between(*C.LOOP_WINDOW) | wide["res_j"].between(*C.LOOP_WINDOW)
    wide["region_i"] = wide["res_i"].map(region_of)
    wide["region_j"] = wide["res_j"].map(region_of)
    def pattern(r):
        return "".join(k for k, p in zip(("W", "V", "T"), C.IDS) if r[f"contact_{p}"])
    wide["pattern_W=5K9W_V=5K9V_T=1T49"] = wide.apply(pattern, axis=1)
    diff = wide[wide["n_structures_in_contact"] < 3].copy()
    # robust differences: contact state differs AND distance changes by > 1 A (not a threshold artefact)
    dcols = [f"min_dist_{p}_A" for p in C.IDS]
    diff["distance_range_A"] = diff[dcols].max(1) - diff[dcols].min(1)
    diff["robust_gt_1A"] = diff["distance_range_A"] > 1.0
    diff.to_csv(C.RESULTS / "contact_differences.csv", index=False)

    # ---- per loop residue summary --------------------------------------------
    rows = []
    for pid in C.IDS:
        c = cm[cm["structure"] == pid]
        for r in range(C.LOOP_WINDOW[0], C.LOOP_WINDOW[1] + 1):
            part = c[(c["res_i"] == r) | (c["res_j"] == r)]
            partners = sorted(set(part["res_i"]) | set(part["res_j"]) - {r}) if len(part) else []
            partners = [x for x in partners if x != r]
            rows.append(dict(structure=pid, resnum=r, resname=P[pid][P[pid]["resnum"] == r]["resname"].iloc[0],
                             n_contact_partners=len(partners), n_partners_outside_window=sum(not (176 <= x <= 187) for x in partners),
                             partners=" ".join(str(x) for x in partners)))
    loop = pd.DataFrame(rows)
    loop.to_csv(C.RESULTS / "loop_contact_summary.csv", index=False)

    # ---- declared distances ---------------------------------------------------
    drows = []
    structures = dict(T)
    notes = {pid: "core set" for pid in C.IDS}
    if extra.exists():
        from Bio.PDB.MMCIF2Dict import MMCIF2Dict
        d = MMCIF2Dict(str(extra))
        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"]})
        structures["1SUG"] = C.select_altloc(t)
        notes["1SUG"] = "supplementary apo control; file retrieved by the independent technician (sources/case/1SUG.cif), not part of the three-structure core set"
    for pid, t in structures.items():
        for label, sa, sb, kind in DISTANCES:
            v, a_, b_ = min_dist(t, sa, sb)
            drows.append(dict(structure=pid, distance=label, kind=kind, value_A=v, atom_a=a_, atom_b=b_,
                              status="measured" if np.isfinite(v) else "not measurable: one group is not modelled in this structure",
                              structure_role=notes[pid]))
    # active-site ligand (5K9W only): TCS401 (OTA) to Asp181 and Cys215
    t = T["5K9W"]
    ota = t[t["resname"] == "OTA"][["x", "y", "z"]].values
    pw = C.protein(t)
    for label, sel in (("TCS401 (OTA) heavy atoms - Cys215 SG (min)", atom(215, "SG")), ("TCS401 (OTA) heavy atoms - Asp181 side chain (min)", sidechain(181)),
                       ("TCS401 (OTA) heavy atoms - Phe182 side chain (min)", sidechain(182)), ("TCS401 (OTA) heavy atoms - loop window 176-187 (min)", res(176, 187))):
        g = pw[sel(pw)]
        D = np.linalg.norm(g[["x", "y", "z"]].values[:, None] - ota[None], axis=-1)
        i, j = np.unravel_index(D.argmin(), D.shape)
        drows.append(dict(structure="5K9W", distance=label, kind="group min", value_A=float(D.min()),
                          atom_a=f"OTA402 {t[t['resname'] == 'OTA']['atom'].iloc[j]}", atom_b=f"{g.iloc[i].resname}{g.iloc[i].resnum} {g.iloc[i].atom}",
                          status="measured", structure_role="core set"))
    dist = pd.DataFrame(drows)
    dist.to_csv(C.RESULTS / "region_distances.csv", index=False)

    pd.set_option("display.width", 250, "display.max_columns", 30, "display.max_rows", 200)
    print("contacts per structure:", cm.groupby("structure").size().to_dict(), "| common-range:", common.groupby("structure").size().to_dict())
    print("contact-state patterns in common range:", wide["pattern_W=5K9W_V=5K9V_T=1T49"].value_counts().to_dict())
    rl = diff[diff["robust_gt_1A"] & diff["involves_loop_window"]]
    print("robust loop-window contact differences:", len(rl), "of", int(diff["robust_gt_1A"].sum()), "robust differences overall")
    print(rl[["res_i", "resname_i", "res_j", "resname_j"] + dcols + ["pattern_W=5K9W_V=5K9V_T=1T49"]].round(2).to_string(index=False))
    print(loop.pivot(index="resnum", columns="structure", values="n_partners_outside_window").to_string())
    print(dist.pivot_table(index="distance", columns="structure", values="value_A", sort=False).round(3).to_string())


if __name__ == "__main__":
    main()
