"""Structure metadata, residue mapping and C-alpha superposition of 5K9W, 5K9V, 1T49.

Core definition (research_plan.md): chain A, C-alpha atoms of identical native
residues 2-280, excluding 176-187 from the fit. Reported per pair: fit RMSD, RMSD
over all compared C-alpha atoms 2-280 in the fitted frame, 176-187 window RMSD in
the fitted frame, and Asp181 displacement. Fit-sensitivity control: the same
quantities with 176-187 included in the fit. A second control prunes the core set
iteratively (C-alpha atoms displaced > 2.0 A are dropped from the fit until convergence).

Outputs: structure_metadata.json, structure_mapping.csv,
results/structural_comparison.csv, results/per_residue_displacement.csv,
results/alpha7_coverage.csv, results/altloc_sensitivity.csv,
results/superposition_transforms.json, processed/<ID>_chainA_in_5K9W_frame.pdb
"""
import json, hashlib, sys
from pathlib import Path
import numpy as np
import pandas as pd

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


def first(d, key, default=None):
    v = d.get(key)
    return v[0] if v else default


def metadata():
    retr = {r["file"]: r for r in json.loads((C.ROOT / "provenance" / "retrieval.json").read_text())}
    out = {}
    for pid in C.IDS:
        d = C.load_cif_dict(pid)
        t = C.atom_table(pid, d)
        p = C.protein(t)
        het = t[(t["group"] == "HETATM") & (t["resname"] != "HOH")]
        ligs = [dict(comp_id=k[0], chain=k[1], auth_seq_id=int(k[2]), n_atoms=int(n))
                for k, n in het.groupby(["resname", "chain", "resnum"]).size().items()]
        names = dict(zip(d.get("_chem_comp.id", []), d.get("_chem_comp.name", [])))
        for l in ligs:
            l["name"] = names.get(l["comp_id"])
        unobs_res = [dict(comp_id=a, auth_seq_id=int(b)) for a, b in zip(
            d.get("_pdbx_unobs_or_zero_occ_residues.auth_comp_id", []),
            d.get("_pdbx_unobs_or_zero_occ_residues.auth_seq_id", []))]
        unobs_atoms = {}
        for a, b, c in zip(d.get("_pdbx_unobs_or_zero_occ_atoms.auth_comp_id", []),
                           d.get("_pdbx_unobs_or_zero_occ_atoms.auth_seq_id", []),
                           d.get("_pdbx_unobs_or_zero_occ_atoms.auth_atom_id", [])):
            unobs_atoms.setdefault(f"{a}{b}", []).append(c)
        alt = p[p["alt"] != "."]
        files = {}
        for fmt in ("cif", "pdb"):
            fn = f"{pid}.{fmt}"
            data = (C.RAW / fn).read_bytes()
            sha = hashlib.sha256(data).hexdigest()
            files[fn] = dict(sha256=sha, bytes=len(data), source_url=retr[fn]["url"],
                             retrieved_utc=retr[fn]["retrieved_utc"],
                             matches_retrieval_record=(sha == retr[fn]["sha256"] and len(data) == retr[fn]["bytes"]))
        out[pid] = dict(
            pdb_id=pid, entry_id_in_file=first(d, "_entry.id"), title=first(d, "_struct.title"),
            state_label=C.STATE[pid], method=first(d, "_exptl.method"),
            resolution_A=float(first(d, "_refine.ls_d_res_high")),
            r_work=float(first(d, "_refine.ls_R_factor_R_work")), r_free=float(first(d, "_refine.ls_R_factor_R_free")),
            space_group=first(d, "_symmetry.space_group_name_H-M"),
            cell_A=[float(first(d, f"_cell.length_{x}")) for x in "abc"],
            data_collection_temperature_K=first(d, "_diffrn.ambient_temp"),
            crystallization=dict(pH=first(d, "_exptl_crystal_grow.pH"), temperature_K=first(d, "_exptl_crystal_grow.temp"),
                                 method=first(d, "_exptl_crystal_grow.method"), details=first(d, "_exptl_crystal_grow.pdbx_details")),
            deposition_date=first(d, "_pdbx_database_status.recvd_initial_deposition_date"),
            primary_citation=dict(title=first(d, "_citation.title"), journal=first(d, "_citation.journal_abbrev"),
                                  year=first(d, "_citation.year"), doi=first(d, "_citation.pdbx_database_id_DOI"),
                                  pubmed=first(d, "_citation.pdbx_database_id_PubMed")),
            uniprot=first(d, "_struct_ref.pdbx_db_accession"),
            construct_residues_auth=[int(first(d, "_struct_ref_seq.pdbx_auth_seq_align_beg")), int(first(d, "_struct_ref_seq.pdbx_auth_seq_align_end"))],
            expression_tag_residues=[int(x) for x, det in zip(d.get("_struct_ref_seq_dif.pdbx_auth_seq_num", []), d.get("_struct_ref_seq_dif.details", [])) if "tag" in det],
            chains_in_file=sorted(set(t["chain"])), chain_analysed=C.CHAIN,
            residue_numbering=dict(scheme="auth_seq_id equals native P18031 numbering",
                                   label_seq_id_minus_auth_seq_id=sorted(int(x) for x in set((p["label_seq"] - p["resnum"]).dropna())),
                                   insertion_codes=False),
            modelled_residue_range=[int(p["resnum"].min()), int(p["resnum"].max())],
            n_modelled_residues=int(p["resnum"].nunique()),
            internal_gaps=sorted(set(range(int(p["resnum"].min()), int(p["resnum"].max()) + 1)) - set(p["resnum"])),
            unobserved_residues=unobs_res, residues_with_unobserved_atoms=unobs_atoms,
            altloc_residues={f"{r[1]}{r[0]}": sorted(set(g["alt"])) + [f"occ={sorted(set(g['occ']))}"] for r, g in alt.groupby(["resnum", "resname"])},
            ligands=ligs, n_waters=int((t["resname"] == "HOH").sum()),
            deposited_helices=[dict(id=i, start=int(b), end=int(e)) for i, b, e in zip(
                d["_struct_conf.pdbx_PDB_helix_id"], d["_struct_conf.beg_auth_seq_id"], d["_struct_conf.end_auth_seq_id"])],
            files=files,
        )
    (C.ROOT / "structure_metadata.json").write_text(json.dumps(out, indent=2))
    return out


def mapping(tables):
    rows = []
    cas = {i: C.ca_coords(tables[i]) for i in C.IDS}
    raw = {i: C.protein(C.atom_table(i)) for i in C.IDS}
    fit = set(C.fit_residue_set(False))
    for r in range(-4, 302):
        row = dict(native_resnum=r)
        names = set()
        for i in C.IDS:
            g = raw[i][raw[i]["resnum"] == r]
            mod = len(g) > 0
            row[f"{i}_resname"] = g["resname"].iloc[0] if mod else ""
            row[f"{i}_modelled"] = mod
            row[f"{i}_label_seq_id"] = int(g["label_seq"].iloc[0]) if mod else ""
            row[f"{i}_n_heavy_atoms"] = int(len(tables[i][(tables[i]["group"] == "ATOM") & (tables[i]["resnum"] == r)])) if mod else 0
            row[f"{i}_altlocs"] = "".join(sorted(set(g["alt"]) - {"."})) if mod else ""
            row[f"{i}_CA_B"] = round(float(g[g["atom"] == "CA"]["b"].mean()), 2) if mod else ""
            if mod:
                names.add(g["resname"].iloc[0])
        n_mod = sum(row[f"{i}_modelled"] for i in C.IDS)
        row["modelled_in_all_three"] = n_mod == 3
        row["identical_residue_where_modelled"] = len(names) <= 1
        row["in_compare_range_2_280"] = C.COMPARE_RANGE[0] <= r <= C.COMPARE_RANGE[1]
        row["in_core_fit_set"] = r in fit
        row["in_loop_window_176_187"] = C.LOOP_WINDOW[0] <= r <= C.LOOP_WINDOW[1]
        row["in_5K9W_deposited_alpha7_285_296"] = C.ALPHA7_DEPOSITED[0] <= r <= C.ALPHA7_DEPOSITED[1]
        if n_mod:
            rows.append(row)
    m = pd.DataFrame(rows)
    m.to_csv(C.ROOT / "structure_mapping.csv", index=False)
    # hard checks on the declared comparison set
    cmp_ = m[m["in_compare_range_2_280"]]
    assert len(cmp_) == 279 and cmp_["modelled_in_all_three"].all() and cmp_["identical_residue_where_modelled"].all()
    assert m["in_core_fit_set"].sum() == 267
    return m


def compare(tables, tag="highest_occupancy"):
    lo, hi = C.COMPARE_RANGE
    allres = list(range(lo, hi + 1))
    loop = list(range(C.LOOP_WINDOW[0], C.LOOP_WINDOW[1] + 1))
    rows, per = [], []
    transforms = {}
    for mob, ref in C.PAIRS:
        cm, cr = C.ca_coords(tables[mob]), C.ca_coords(tables[ref])
        tm, tr = C.protein(tables[mob]), C.protein(tables[ref])
        for fitname in ("core_2-280_excl_176-187", "loop_included_2-280", "pruned_core_iterative_2A"):
            if fitname.startswith("pruned"):
                # second control: start from the core set and iteratively drop C-alpha atoms displaced > 2.0 A
                res = C.fit_residue_set(False)
                for _ in range(50):
                    R, t, fit_rmsd = C.kabsch(np.array([cm[r][1] for r in res]), np.array([cr[r][1] for r in res]))
                    keep = [r for r in res if np.linalg.norm(C.apply(R, t, cm[r][1]) - cr[r][1]) <= 2.0]
                    if len(keep) == len(res):
                        break
                    res = keep
            else:
                R, t, fit_rmsd, res = C.core_transform(tables, mob, ref, fitname.startswith("loop_included"))
            X = {r: C.apply(R, t, cm[r][1]) for r in allres}
            disp = {r: float(np.linalg.norm(X[r] - cr[r][1])) for r in allres}
            # local (window-only) refit separates loop shape change from loop displacement
            _, _, loop_local = C.kabsch(np.array([cm[r][1] for r in loop]), np.array([cr[r][1] for r in loop]))
            # backbone N,CA,C,O over 2-280 in the same frame
            def bb(tt):
                g = tt[tt["resnum"].between(lo, hi) & tt["atom"].isin(C.BACKBONE)].set_index(["resnum", "atom"])
                return g[["x", "y", "z"]]
            bm, br = bb(tm), bb(tr)
            idx = bm.index.intersection(br.index)
            bb_rmsd = C.rmsd(C.apply(R, t, bm.loc[idx].values), br.loc[idx].values)
            def atom_disp(resnum, atom):
                a = tm[(tm["resnum"] == resnum) & (tm["atom"] == atom)][["x", "y", "z"]].values
                b = tr[(tr["resnum"] == resnum) & (tr["atom"] == atom)][["x", "y", "z"]].values
                return float(np.linalg.norm(C.apply(R, t, a[0]) - b[0])) if len(a) == 1 and len(b) == 1 else np.nan
            worst = max(disp, key=disp.get)
            nonloop = [disp[r] for r in allres if r not in loop]
            worst_out = max((r for r in allres if r not in loop), key=disp.get)
            rows.append(dict(
                mobile=mob, reference=ref, fit_definition=fitname, altloc_policy=tag,
                n_fit_CA=len(res), fit_rmsd_A=fit_rmsd,
                n_compared_CA=len(allres), rmsd_all_CA_2_280_A=float(np.sqrt(np.mean([d * d for d in disp.values()]))),
                n_loop_CA=len(loop), loop_176_187_rmsd_fitted_frame_A=float(np.sqrt(np.mean([disp[r] ** 2 for r in loop]))),
                loop_176_187_rmsd_local_refit_A=loop_local,
                asp181_CA_displacement_A=disp[C.ASP181], asp181_CG_displacement_A=atom_disp(C.ASP181, "CG"),
                n_backbone_atoms=len(idx), backbone_NCACO_rmsd_2_280_A=bb_rmsd,
                max_CA_displacement_A=disp[worst], max_CA_displacement_residue=f"{cm[worst][0]}{worst}",
                max_CA_displacement_outside_loop_A=disp[worst_out], max_CA_displacement_outside_loop_residue=f"{cm[worst_out][0]}{worst_out}",
                residues_outside_loop_over_2A=" ".join(str(r) for r in allres if r not in loop and disp[r] > 2.0),
                median_CA_displacement_outside_loop_A=float(np.median(nonloop)),
                n_CA_outside_loop_over_2A=int(sum(d > 2.0 for d in nonloop)),
            ))
            for r in allres:
                per.append(dict(mobile=mob, reference=ref, fit_definition=fitname, resnum=r, resname=cm[r][0],
                                ca_displacement_A=disp[r], in_fit=r in set(res), in_loop_window=r in loop,
                                b_CA_mobile=float(tm[(tm["resnum"] == r) & (tm["atom"] == "CA")]["b"].iloc[0]),
                                b_CA_reference=float(tr[(tr["resnum"] == r) & (tr["atom"] == "CA")]["b"].iloc[0])))
            transforms[f"{mob}_onto_{ref}__{fitname}"] = dict(rotation=R.tolist(), translation=t.tolist(), fit_rmsd_A=fit_rmsd,
                                                              convention="x_fitted = R @ x + t")
    return pd.DataFrame(rows), pd.DataFrame(per), transforms


def alpha7(tables, meta):
    rows = []
    for r in range(276, 302):
        row = dict(native_resnum=r, in_5K9W_deposited_alpha7=C.ALPHA7_DEPOSITED[0] <= r <= C.ALPHA7_DEPOSITED[1])
        for i in C.IDS:
            p = C.protein(tables[i])
            g = p[p["resnum"] == r]
            in_construct = meta[i]["construct_residues_auth"][0] <= r <= meta[i]["construct_residues_auth"][1]
            row[f"{i}_status"] = "modelled" if len(g) else ("in construct, not modelled" if in_construct else "not in construct")
            row[f"{i}_resname"] = g["resname"].iloc[0] if len(g) else ""
            row[f"{i}_n_atoms"] = int(len(g))
            row[f"{i}_mean_B"] = round(float(g["b"].mean()), 2) if len(g) else ""
            hel = [h["id"] for h in meta[i]["deposited_helices"] if h["start"] <= r <= h["end"]]
            row[f"{i}_deposited_helix_id"] = hel[0] if hel else ""
        rows.append(row)
    a7 = pd.DataFrame(rows)
    a7.to_csv(C.RESULTS / "alpha7_coverage.csv", index=False)
    return a7


def write_pdb(t, path, R=None, tvec=None, remark=""):
    xyz = t[["x", "y", "z"]].values
    if R is not None:
        xyz = C.apply(R, tvec, xyz)
    lines = [f"REMARK   {l}" for l in remark.split("\n") if l]
    for n, (r, c) in enumerate(zip(t.itertuples(), xyz), 1):
        name = r.atom if len(r.atom) == 4 or len(r.element) == 2 else " " + r.atom
        rec = "ATOM  " if r.group == "ATOM" else "HETATM"
        lines.append(f"{rec}{n % 100000:5d} {name:<4s} {r.resname:>3s} {r.chain}{r.resnum:4d}    "
                     f"{c[0]:8.3f}{c[1]:8.3f}{c[2]:8.3f}{r.occ:6.2f}{r.b:6.2f}          {r.element:>2s}")
    lines.append("END")
    Path(path).write_text("\n".join(lines) + "\n")


def main():
    meta = metadata()
    tables = C.load_all("highest_occupancy")
    m = mapping(tables)
    comp, per, transforms = compare(tables)
    comp.to_csv(C.RESULTS / "structural_comparison.csv", index=False)
    per.to_csv(C.RESULTS / "per_residue_displacement.csv", index=False)
    (C.RESULTS / "superposition_transforms.json").write_text(json.dumps(transforms, indent=1))
    a7 = alpha7(tables, meta)
    # altloc sensitivity: repeat the core comparison choosing conformer A or B everywhere
    sens = []
    for pol in ("A", "B"):
        c2, _, _ = compare(C.load_all(pol), tag=f"altloc_{pol}")
        sens.append(c2)
    sens = pd.concat([comp] + sens)
    sens.to_csv(C.RESULTS / "altloc_sensitivity.csv", index=False)
    # coordinates in the common 5K9W frame (core fit) for the viewers; waters dropped
    for pid in C.IDS:
        t = tables[pid]
        t = t[t["resname"] != "HOH"]
        if pid == "5K9W":
            R, tv = np.eye(3), np.zeros(3)
            note = "5K9W chain A, deposited frame (reference)."
        else:
            R, tv, f, res = C.core_transform(tables, pid, "5K9W", False)
            note = f"{pid} chain A rigidly superposed onto 5K9W; Kabsch fit on {len(res)} CA atoms (2-280 excl. 176-187), fit RMSD {f:.3f} A."
        write_pdb(t, C.PROCESSED / f"{pid}_chainA_in_5K9W_frame.pdb", R, tv,
                  remark=note + "\nExperimental coordinates; rigid-body transform only. One conformer per residue (highest occupancy).\nGenerated by analysis/structure_alignment.py")
    pd.set_option("display.width", 250, "display.max_columns", 30)
    core = comp[comp.fit_definition.str.startswith("core")]
    print(core[["mobile", "reference", "n_fit_CA", "fit_rmsd_A", "rmsd_all_CA_2_280_A", "loop_176_187_rmsd_fitted_frame_A",
                "loop_176_187_rmsd_local_refit_A", "asp181_CA_displacement_A", "asp181_CG_displacement_A"]].round(3).to_string(index=False))
    print(comp[["mobile", "reference", "fit_definition", "fit_rmsd_A", "rmsd_all_CA_2_280_A", "loop_176_187_rmsd_fitted_frame_A",
                "asp181_CA_displacement_A", "backbone_NCACO_rmsd_2_280_A", "max_CA_displacement_A", "max_CA_displacement_outside_loop_A", "max_CA_displacement_outside_loop_residue",
                "residues_outside_loop_over_2A", "n_fit_CA"]].round(3).to_string(index=False))
    print("altloc sensitivity (core fit):")
    print(sens[sens.fit_definition.str.startswith("core")][["mobile", "reference", "altloc_policy", "fit_rmsd_A", "rmsd_all_CA_2_280_A",
                                                             "loop_176_187_rmsd_fitted_frame_A", "asp181_CA_displacement_A"]].round(4).to_string(index=False))
    print(a7[[c for c in a7.columns if c.endswith("status") or c == "native_resnum"]].to_string(index=False))
    return comp


if __name__ == "__main__":
    main()
