"""Run PROCHECK 3.5.4 on the three sperm whale myoglobin models used in the
ProteinIQ MolProbity score guide, so the PROCHECK and MolProbity numbers in
the MolProbity vs PROCHECK guide come from the same coordinate files.

PROCHECK is compiled from Roman Laskowski's source release
(https://github.com/RomanLas/PROCHECK, procheck.tar.gz, v3.5.4) with gfortran
in a Debian image on Modal. Each structure is downloaded from RCSB PDB or the
AlphaFold Protein Structure Database and run with procheck.scr at the given
resolution. The .sum file of each run is printed and returned.

The tarball's scripts report v3.5.4, although pplot.f also carries the v3.6
option for newer Ramachandran regions. The shipped procheck.prm has no
'Ramachandran regions' keyword, so pplot logs a warning and keeps its default
(NEWREG = .FALSE.): the classic Morris et al. (1992) regions are used.
The published run used Debian's gfortran from debian_slim (Python 3.11 image)
on Modal, 2026-11-18.

Usage: modal run run_procheck_modal.py
"""

import modal

# Commit of RomanLas/PROCHECK that was main when the published numbers were made.
PROCHECK_COMMIT = "9aeb8b630e36f84ac7fc00855afb956f3699077a"
PROCHECK_COMMIT_URL = f"https://github.com/RomanLas/PROCHECK/raw/{PROCHECK_COMMIT}/procheck.tar.gz"

image = (
    modal.Image.debian_slim(python_version="3.11")
    .apt_install("gfortran", "gcc", "make", "tcsh", "curl", "ca-certificates")
    .run_commands(
        "mkdir -p /opt/procheck && cd /opt && curl -sL -o procheck.tar.gz " + PROCHECK_COMMIT_URL,
        "cd /opt && tar xzf procheck.tar.gz && ls /opt",
        "cd /opt/procheck && make F77=gfortran CC=gcc "
        "FOPTS='-std=legacy -fno-automatic -O1 -w' COPTS='-O1 -w' procheck 2>&1 | tail -5",
        "ls /opt/procheck && gfortran --version | head -1",
    )
)

app = modal.App("guide-procheck-myoglobin", image=image)

STRUCTURES = [
    # (label, resolution passed to PROCHECK, download URL)
    ("1MBN", "2.0", "https://files.rcsb.org/download/1MBN.pdb"),
    ("1A6M", "1.0", "https://files.rcsb.org/download/1A6M.pdb"),
    # PROCHECK needs a resolution; 2.0 is used for the prediction. It changes
    # only the resolution band the G-factor plots compare against, not the
    # Ramachandran region counts.
    ("AF-P02185-F1", "2.0", "https://alphafold.ebi.ac.uk/files/AF-P02185-F1-model_v6.pdb"),
]


@app.function(timeout=600)
def run_all() -> dict:
    import os
    import subprocess
    import urllib.request
    from pathlib import Path

    env = dict(os.environ, prodir="/opt/procheck/")
    results = {}
    for label, resolution, url in STRUCTURES:
        work = Path("/tmp") / label
        work.mkdir(parents=True, exist_ok=True)
        req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
        pdb = work / f"{label.lower()}.pdb"
        pdb.write_bytes(urllib.request.urlopen(req, timeout=60).read())
        proc = subprocess.run(
            ["tcsh", "/opt/procheck/procheck.scr", pdb.name, resolution],
            cwd=work, env=env, capture_output=True, text=True, timeout=300,
        )
        files = {}
        for f in sorted(work.iterdir()):
            if f.suffix in {".sum", ".log", ".out", ".rin", ".nb", ".pln", ".lan"} or f.name.endswith(".sum"):
                files[f.name] = f.read_text(errors="replace")
        results[label] = {"stdout": proc.stdout[-4000:], "stderr": proc.stderr[-2000:], "files": files}
    return results


@app.local_entrypoint()
def main(out_dir: str = "procheck_out"):
    from pathlib import Path

    out = Path(out_dir)
    out.mkdir(exist_ok=True)
    results = run_all.remote()
    for label, r in results.items():
        (out / f"{label}_stdout.txt").write_text(r["stdout"] + "\n--- stderr ---\n" + r["stderr"])
        for name, text in r["files"].items():
            (out / f"{label}__{name}").write_text(text)
        sums = [t for n, t in r["files"].items() if n.endswith(".sum")]
        print(f"===== {label}")
        print(sums[0] if sums else r["stdout"][-1500:])
