"""Regenerate the Model page's mCherry structure-view data.

Run with Python and ViennaRNA 2.7.2 installed. The RNA coordinates are an
illustrative lift of ViennaRNA's 2D secondary-structure plot, not a tertiary
structure prediction. Protein C-alpha coordinates come from PDB 2H5Q.
"""

import hashlib
import json
import math
from pathlib import Path
from urllib.request import urlopen

import RNA


ROOT = Path(__file__).resolve().parent
assert RNA.__version__ == "2.7.2", RNA.__version__
sequence = "".join(ROOT.joinpath("mcherry.fasta").read_text().splitlines()[1:]).strip()
assert len(sequence) == 711

structure, energy = RNA.fold(sequence)
coords = RNA.get_xy_coordinates(structure)
probabilities = RNA.pfl_fold_up(sequence, 20, 200, 150)

# ViennaRNA returns one coordinate per residue, indexed from zero. The small
# sinusoidal depth keeps the paired-base drawing legible when tilted; it has
# no physical scale or biological interpretation.
rna_positions = []
for index in range(len(sequence)):
    point = coords.get(index)
    rna_positions.append([
        round(point.X, 2),
        round(point.Y, 2),
        round(14 * math.sin(index * 0.067), 2),
    ])

recorded = json.loads(ROOT.joinpath("result.json").read_text())
candidates = []
for candidate in sorted(
    (c for c in recorded["candidates"] if isinstance(c.get("rank"), int)),
    key=lambda c: c["rank"],
):
    feature = candidate["triggers"]["features"][0]
    candidates.append({
        "rank": candidate["rank"],
        "ref": candidate["ref"],
        "start": feature["start_index"] + 1,
        "end": feature["start_index"] + len(feature["sequence"]),
        "score": round(candidate["overall_score"], 4),
    })

rna_data = {
    "source": "Recorded mCherry input sequence and ranked candidates in this directory",
    "sequence_sha256": hashlib.sha256(sequence.encode()).hexdigest(),
    "length": len(sequence),
    "model": "ViennaRNA 2.7.2 RNAfold MFE at 37 C; RNAplfold pU(1) W=200 L=150 u=20 at 37 C",
    "layout": "ViennaRNA 2D secondary-structure coordinates with artificial display-only depth; not RNA 3D coordinates",
    "mfe_kcal_mol": energy,
    "structure": structure,
    "positions": rna_positions,
    "p_unpaired": [round(float(probabilities[i + 1][1]), 5) for i in range(len(sequence))],
    "candidates": candidates,
}
ROOT.joinpath("rna-structure-view.json").write_text(json.dumps(rna_data, separators=(",", ":")) + "\n")

pdb_url = "https://files.rcsb.org/download/2H5Q.pdb"
with urlopen(pdb_url) as response:
    pdb_bytes = response.read()
pdb_sha256 = hashlib.sha256(pdb_bytes).hexdigest()
assert pdb_sha256 == "e4c13f86d4133f0c3391ec49df9ad302ce091528d81729356d07e8250a38557e", pdb_sha256
pdb = pdb_bytes.decode("ascii")

# Use the deposited HELIX/SHEET assignments, deduplicating sheet records.
secondary_structure = []
for line in pdb.splitlines():
    if line.startswith("HELIX ") and line[19] == "A" and line[31] == "A":
        element = {"type": "helix", "start": int(line[21:25]), "end": int(line[33:37])}
    elif line.startswith("SHEET ") and line[21] == "A" and line[32] == "A":
        element = {"type": "sheet", "start": int(line[22:26]), "end": int(line[33:37])}
    else:
        continue
    if element not in secondary_structure:
        secondary_structure.append(element)
secondary_structure.sort(key=lambda element: element["start"])

residues = []
seen = set()
for line in pdb.splitlines():
    if not line.startswith("ATOM  ") or line[12:16].strip() != "CA" or line[21] != "A":
        continue
    if line[16] not in (" ", "A"):
        continue
    key = line[22:27].strip()
    if key in seen:
        continue
    seen.add(key)
    residues.append({
        "residue": key,
        "name": line[17:20].strip(),
        "xyz": [round(float(line[i:i + 8]), 3) for i in (30, 38, 46)],
    })

protein_data = {
    "source": pdb_url,
    "pdb_file_sha256": pdb_sha256,
    "pdb_id": "2H5Q",
    "method": "X-ray diffraction",
    "resolution_angstrom": 1.36,
    "chain": "A",
    "representation": "Secondary-structure cartoon from C-alpha coordinates and deposited HELIX/SHEET records; chromophore and other atoms omitted",
    "secondary_structure": secondary_structure,
    "residues": residues,
}
ROOT.joinpath("protein-structure-view.json").write_text(json.dumps(protein_data, separators=(",", ":")) + "\n")
print(f"RNA: {len(sequence)} nt, MFE {energy} kcal/mol; protein: {len(residues)} CA atoms")
print("Top candidate:", candidates[0], "mean pU(1):", sum(rna_data["p_unpaired"][653:689]) / 36)
