"""Verify the exact local package and its preparation/resume boundary.

Preparation uses an empty stand-in assets directory and never launches native
gameplay. Native effects, save serialization and AP delivery have separate tests.
"""
from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
import tempfile
import zipfile

TOOLKIT = "ac39b39f296b073553ecd4f9c486b9d14beda9eb"
WORLD = "bc09ac0a3a3eff36d99d8d6dc492fbcf40218f82361f56773112b5f173a89d9f"
REQUIRED = {
    "bin/pikmin2-native.exe", "bin/pikmin2_fusion.exe", "bin/SDL2.dll",
    "bin/libgcc_s_seh-1.dll", "bin/libstdc++-6.dll", "bin/libwinpthread-1.dll",
    "Play.cmd", "Play.ps1", "README.md", "source/Cargo.toml", "source/Cargo.lock",
    "source/contract.json", "source/src/lib.rs", "source/src/main.rs",
    "source/native.patch",
}
FORBIDDEN = {".iso", ".gcm", ".wbfs", ".dol", ".rarc", ".szs", ".bti", ".bmd",
             ".bck", ".raw", ".gci", ".apworld", ".appik2", ".archipelago", ".apsave", ".gosave"}


def digest(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def verify(package):
    package = Path(package).resolve(strict=True)
    manifest = json.loads((package / "manifest.json").read_text(encoding="utf-8"))
    assert manifest["format"] in {"pikmin2-fusion-local-pilot-v1", "pikmin2-fusion-candidate-v1"}
    assert manifest["published"] is False
    assert manifest["game_assets_included"] is False
    assert manifest["toolkit_revision"] == TOOLKIT
    assert manifest["upstream_apworld"] == {"release": "v0.9.1", "sha256": WORLD, "bundled": False}
    names = set(manifest["files"])
    assert REQUIRED <= names, sorted(REQUIRED - names)
    actual = set()
    for path in package.rglob("*"):
        assert not path.is_symlink() and not path.is_junction(), path
        if not path.is_file():
            continue
        name = path.relative_to(package).as_posix()
        actual.add(name)
        assert path.suffix.lower() not in FORBIDDEN, name
        assert name == "manifest.json" or name in names, name
    assert actual == names | {"manifest.json"}
    for name, expected in manifest["files"].items():
        path = package / name
        assert path.resolve().is_relative_to(package), name
        assert path.is_file(), name
        assert path.stat().st_size == expected["bytes"], name
        assert digest(path) == expected["sha256"], name
    for name in ("bin/pikmin2-native.exe", "bin/pikmin2_fusion.exe"):
        assert (package / name).read_bytes()[:2] == b"MZ", name
    archive_path = package.with_suffix(".zip")
    assert archive_path.is_file(), "exact package archive missing"
    with zipfile.ZipFile(archive_path) as archive:
        archive_names = archive.namelist()
        assert len(archive_names) == len(set(archive_names)), "duplicate archive entries"
        assert set(archive_names) == actual
        assert archive.read("manifest.json") == (package / "manifest.json").read_bytes()
        for name, expected in manifest["files"].items():
            data = archive.read(name)
            assert len(data) == expected["bytes"], name
            assert hashlib.sha256(data).hexdigest() == expected["sha256"], name
    catalog = json.loads((package / "source/contract.json").read_text(encoding="utf-8"))
    assert catalog["apworld_sha256"] == WORLD
    assert catalog["game"] == "Pikmin 2"
    if manifest.get("stage") == "release-candidate":
        report = json.loads((package / "source/evidence/gameplay.json").read_text(encoding="utf-8"))
        assert report["status"] == "passed"
        assert report["native_sha256"] == digest(package / "bin/pikmin2-native.exe")
        assert report["client_sha256"] == digest(package / "bin/pikmin2_fusion.exe")
        assert report["native_runtime_sha256"] == {path.name:digest(path) for path in (package/"bin").glob("*.dll")}, "gameplay evidence DLLs differ from packaged runtime"
        for gate in ("normal_entry", "carrying", "local_remote_delivery", "progression",
                     "water_blue_only", "physical_replacements", "reconnect",
                     "card_save_load_restart", "original_goals"):
            assert report["gates"][gate]["passed"] is True, gate
    return {"files": len(names), "required_source_inputs": True, "archive_sha256": digest(archive_path),
            "package_native_sha256": digest(package / "bin/pikmin2-native.exe"),
            "package_client_sha256": digest(package / "bin/pikmin2_fusion.exe"),
            "boundary": "manifest/allowlist and source-input verification; no gameplay asserted"}


def prepare_resume(package, patch, powershell):
    package = Path(package).resolve(strict=True)
    patch = Path(patch).resolve(strict=True)
    with tempfile.TemporaryDirectory(prefix="Pikmin 2 package with spaces ") as temporary:
        root = Path(temporary)
        assets = root / "empty assets fixture"
        assets.mkdir()
        run = root / "selected run with spaces"
        save = root / "selected save with spaces"
        selected_patch = root / "original seed with spaces.appik2"
        shutil.copyfile(patch, selected_patch)
        command = [str(powershell), "-NoProfile", "-File", str(package / "Play.ps1"),
                   "-Appik2", str(selected_patch), "-Server", "ws://127.0.0.1:38291", "-Assets", str(assets),
                   "-RunDirectory", str(run), "-SaveDirectory", str(save),
                   "-SaveToken", "player-selected-pilot-save", "-PrepareOnly"]
        first = subprocess.run(command, capture_output=True, timeout=30)
        if first.returncode:
            raise AssertionError(first.stderr.decode(errors="replace"))
        profile_path = run / "profile.json"
        config_path = run / "bridge/runtime-config.json"
        before = {"profile": profile_path.read_bytes(), "config": config_path.read_bytes()}
        profile = json.loads(before["profile"])
        config = json.loads(before["config"])
        with zipfile.ZipFile(selected_patch) as original:
            expected_patch = json.loads(original.read("patch.appik2"))
        assert config["patch"] == expected_patch
        assert config["toolkit_revision"] == TOOLKIT
        assert config["apworld_sha256"] == WORLD
        assert profile["save"] == "player-selected-pilot-save"
        assert profile["slot_name"] == expected_patch["slot_name"]
        assert set(profile["locations"]) == set(range(1, 202))
        marker = save / "prepare-only-preservation-control.bin"
        marker.write_bytes(b"fixture save-directory marker; no native save format claimed")
        second = subprocess.run(command, capture_output=True, timeout=30)
        if second.returncode:
            raise AssertionError(second.stderr.decode(errors="replace"))
        assert profile_path.read_bytes() == before["profile"]
        assert config_path.read_bytes() == before["config"]
        assert marker.read_bytes() == b"fixture save-directory marker; no native save format claimed"
        assert (run / "game/assets").is_dir()
        assert not list(run.glob("native-*.log")), "PrepareOnly must not start native gameplay"
        return {"prepare_only_with_spaces": True, "resume_preserves_profile_config": True,
                "save_directory_marker_preserved": True,
                "boundary": "actual packaged client/launcher preparation only; empty assets stand-in, no native gameplay"}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--package", type=Path, required=True)
    parser.add_argument("--patch", type=Path)
    parser.add_argument("--powershell", default="powershell.exe")
    arguments = parser.parse_args()
    report = verify(arguments.package)
    if arguments.patch:
        report["launcher"] = prepare_resume(arguments.package, arguments.patch, arguments.powershell)
    print(json.dumps(report, indent=2))
