"""Shared helpers for the PTP1B structural comparison (primary pipeline, mmCIF input).

Primary measurements read the deposited mmCIF files with Bio.PDB.MMCIF2Dict and
superpose with a NumPy SVD (Kabsch) fit. The independent check in
verification_tests.py deliberately does NOT import this module.
"""
from pathlib import Path
import numpy as np
import pandas as pd
from Bio.PDB.MMCIF2Dict import MMCIF2Dict

ROOT = Path(__file__).resolve().parents[1]
RAW = ROOT / "data" / "raw"
RESULTS = ROOT / "results"
PROCESSED = ROOT / "processed"
FIGURES = ROOT / "figures"
for _d in (RESULTS, PROCESSED, FIGURES):
    _d.mkdir(exist_ok=True)

IDS = ("5K9W", "5K9V", "1T49")
STATE = {
    "5K9W": "TCS401 (OTA) active-site complex; deposited title 'closed state'",
    "5K9V": "no active-site ligand; deposited title 'open state'",
    "1T49": "distal inhibitor (ligand 892) complex",
}
CHAIN = "A"
# Declared residue sets (native P18031 numbering == auth_seq_id in all three files)
COMPARE_RANGE = (2, 280)          # residues modelled in all three depositions
LOOP_WINDOW = (176, 187)          # WPD-loop window excluded from the core fit
ASP181 = 181
CYS215 = 215
ALPHA7_DEPOSITED = (285, 296)     # helix AB2 in the 5K9W struct_conf records
PAIRS = (("5K9V", "5K9W"), ("1T49", "5K9W"), ("1T49", "5K9V"))  # (mobile, reference)
BACKBONE = ("N", "CA", "C", "O")


def load_cif_dict(pdb_id):
    return MMCIF2Dict(str(RAW / f"{pdb_id}.cif"))


def atom_table(pdb_id, cif=None):
    """All model-1 atoms as a DataFrame with numeric columns (no altloc filtering)."""
    d = cif or load_cif_dict(pdb_id)
    a = pd.DataFrame({k.split(".")[1]: d[k] for k in d if k.startswith("_atom_site.")})
    a = a[a["pdbx_PDB_model_num"] == a["pdbx_PDB_model_num"].iloc[0]].copy()
    t = pd.DataFrame({
        "group": a["group_PDB"].values,
        "chain": a["auth_asym_id"].values,
        "resnum": a["auth_seq_id"].astype(int).values,
        "label_seq": pd.to_numeric(a["label_seq_id"], errors="coerce").values,
        "resname": a["auth_comp_id"].values,
        "atom": a["label_atom_id"].str.strip('"').values,
        "alt": a["label_alt_id"].values,
        "occ": a["occupancy"].astype(float).values,
        "b": a["B_iso_or_equiv"].astype(float).values,
        "x": a["Cartn_x"].astype(float).values,
        "y": a["Cartn_y"].astype(float).values,
        "z": a["Cartn_z"].astype(float).values,
        "element": a["type_symbol"].values,
    })
    return t


def select_altloc(t, policy="highest_occupancy"):
    """Keep one conformer per residue.

    policy 'highest_occupancy': per residue, keep the altloc label with the highest
    mean occupancy (ties -> alphabetically first label). policy 'A'/'B': keep that
    label where present. Atoms without an altloc label ('.') are always kept.
    """
    keep = t["alt"] == "."
    alts = t[~keep]
    if len(alts):
        for (chain, resnum, resname), g in alts.groupby(["chain", "resnum", "resname"]):
            if policy == "highest_occupancy":
                m = g.groupby("alt")["occ"].mean()
                best = sorted(m.index, key=lambda k: (-round(m[k], 4), k))[0]
            else:
                best = policy if policy in set(g["alt"]) else sorted(set(g["alt"]))[0]
            keep.loc[g.index[g["alt"] == best]] = True
    return t[keep].copy()


def protein(t):
    return t[(t["group"] == "ATOM") & (t["chain"] == CHAIN)]


def ca_coords(t):
    """dict resnum -> (resname, xyz) for C-alpha atoms of the protein chain."""
    p = protein(t)
    ca = p[p["atom"] == "CA"]
    assert not ca["resnum"].duplicated().any(), "duplicate CA after altloc selection"
    return {int(r.resnum): (r.resname, np.array([r.x, r.y, r.z])) for r in ca.itertuples()}


def kabsch(mobile, ref):
    """Least-squares rigid fit of mobile (N,3) onto ref (N,3) by SVD.

    Returns R (3x3), t (3,) with fitted = mobile @ R.T + t, and the fit RMSD.
    """
    mobile = np.asarray(mobile, float)
    ref = np.asarray(ref, float)
    assert mobile.shape == ref.shape and mobile.shape[0] >= 3
    mc, rc = mobile.mean(0), ref.mean(0)
    H = (mobile - mc).T @ (ref - rc)
    U, S, Vt = np.linalg.svd(H)
    d = np.sign(np.linalg.det(Vt.T @ U.T))
    R = Vt.T @ np.diag([1.0, 1.0, d]) @ U.T
    t = rc - R @ mc
    fitted = mobile @ R.T + t
    return R, t, float(np.sqrt(((fitted - ref) ** 2).sum(1).mean()))


def rmsd(a, b):
    a, b = np.asarray(a, float), np.asarray(b, float)
    return float(np.sqrt(((a - b) ** 2).sum(1).mean()))


def fit_residue_set(include_loop=False):
    lo, hi = COMPARE_RANGE
    res = list(range(lo, hi + 1))
    if not include_loop:
        res = [r for r in res if not (LOOP_WINDOW[0] <= r <= LOOP_WINDOW[1])]
    return res


def core_transform(tables, mobile, ref, include_loop=False):
    """Rigid transform of `mobile` onto `ref` using the declared C-alpha fit set."""
    cm, cr = ca_coords(tables[mobile]), ca_coords(tables[ref])
    res = fit_residue_set(include_loop)
    for r in res:
        assert cm[r][0] == cr[r][0], f"residue identity mismatch at {r}"
    R, t, fit_rmsd = kabsch(np.array([cm[r][1] for r in res]), np.array([cr[r][1] for r in res]))
    return R, t, fit_rmsd, res


def apply(R, t, xyz):
    return np.asarray(xyz, float) @ R.T + t


def load_all(policy="highest_occupancy"):
    return {i: select_altloc(atom_table(i), policy) for i in IDS}
