import os
import shutil
import subprocess
import tempfile
from pathlib import Path

import pytest
import modrna_params as mp

_TLEAP = shutil.which("tleap")
_AMBERHOME = str(Path(_TLEAP).resolve().parent.parent) if _TLEAP else None
_OL3 = (Path(_AMBERHOME) / "dat/leap/cmd/leaprc.RNA.OL3") if _AMBERHOME else None

pytestmark = pytest.mark.skipif(
    not _TLEAP or not (_OL3 and _OL3.exists()),
    reason="AmberTools tleap / leaprc.RNA.OL3 not available",
)

# each form placed at its correct chain position; {u} = the modified unit
_SEQ = {
    "internal": "G5 {u} G3",
    "5prime": "{u} G G3",
    "3prime": "G5 G {u}",
}


@pytest.mark.parametrize("res", mp.RESIDUES)
@pytest.mark.parametrize("term", mp.TERMINI)
def test_tleap_build(res, term):
    assert _TLEAP and _AMBERHOME  # guaranteed by the module-level skipif
    unit = mp.unit_name(res, term)
    seq = _SEQ[term].format(u=unit)
    script = "\n".join([
        "source leaprc.RNA.OL3",
        *mp.leaprc_lines(),
        f"x = sequence {{ {seq} }}",
        "saveamberparm x out.prmtop out.inpcrd",
        "quit",
    ])
    with tempfile.TemporaryDirectory() as td:
        Path(td, "b.leap").write_text(script)
        env = dict(os.environ, AMBERHOME=_AMBERHOME)
        env["PATH"] = (str(Path(_AMBERHOME) / "bin") + os.pathsep
                       + env.get("PATH", ""))
        proc = subprocess.run([_TLEAP, "-f", "b.leap"], cwd=td, env=env,
                              capture_output=True, text=True)
        log = proc.stdout + proc.stderr
        assert Path(td, "out.prmtop").exists(), log[-3000:]
        for bad in ("Could not find", "No torsion", "not saved"):
            assert bad not in log, f"{bad} in tleap log:\n{log[-2000:]}"
