#!/usr/bin/env python3
"""PepSilico SAPIEN-Pep V18 installer helper.
Requires the separately supplied frozen ZIP; does not download engine source.
"""
import argparse, hashlib, json, zipfile
from pathlib import Path

EXPECTED_ARCHIVE_SHA256 = "a375f45957687617d361f73f5d0168328ef5d6e79f12b27070effaa553a95be5"
PREFIX = "SAPIEN_PEP_V18_BASE_FROZEN_20261103/"

def main():
    parser = argparse.ArgumentParser(description="Install a verified locally supplied SAPIEN-Pep V18 freeze")
    parser.add_argument("archive", type=Path, help="SAPIEN_PEP_V18_BASE_FROZEN_20261103.zip")
    parser.add_argument("--destination", type=Path, default=Path.home() / "sapien_pep_v18_frozen")
    parser.add_argument("--check-only", action="store_true")
    args = parser.parse_args()
    package = args.archive.expanduser().resolve()
    if not package.is_file():
        parser.error("Cannot find the frozen ZIP: " + str(package))
    digest = hashlib.sha256(package.read_bytes()).hexdigest()
    if digest != EXPECTED_ARCHIVE_SHA256:
        raise SystemExit("SHA-256 mismatch. Obtain the matching verified frozen ZIP.")
    with zipfile.ZipFile(package) as archive:
        manifest = json.loads(archive.read(PREFIX + "MANIFEST_SHA256.json"))
        for name, expected in manifest["files"].items():
            actual = hashlib.sha256(archive.read(PREFIX + name)).hexdigest()
            if actual != expected:
                raise SystemExit("Payload integrity check failed: " + name)
        print("Verified frozen archive and", len(manifest["files"]), "payload files")
        if args.check_only:
            return
        destination = args.destination.expanduser().resolve()
        if destination.exists() and any(destination.iterdir()):
            raise SystemExit("Destination exists and is not empty. Select a fresh directory.")
        for info in archive.infolist():
            target = (destination / info.filename).resolve()
            if not target.is_relative_to(destination):
                raise SystemExit("Unsafe archive path detected")
        destination.mkdir(parents=True, exist_ok=True)
        archive.extractall(destination)
    print("Installed:", destination / PREFIX)
    print("For ACE replay, install numpy pandas openpyxl; then run verified_ace_standard/replay.py")
    print("DPP-IV parity with the independent specialist is not yet verified.")

if __name__ == "__main__":
    main()
