#!/usr/bin/env python3
"""Repair known Metal device handoffs in the Simoji dev4 Isaac Lab source package.

Uses the installed environment's Python and its existing dependencies; no network,
package installation, app changes, or physics-device changes are performed.
"""

from __future__ import annotations

import argparse
import datetime
import hashlib
import json
import os
from pathlib import Path
import stat
import tempfile


PAIR = {"schema": 1, "release_id": "simoji-1.0-dev4", "api_protocol": 1, "native_abi": "1.19.0"}
DEFAULT_SDK = "Simoji/IsaacLab-Simoji-simoji-1.0-dev4"
REPAIRS = (
    {
        "path": "source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py",
        "before": "389b248b4ed8bfe1be0e9b3ca2440866a54c26ac6ec7e55cf24ebe41691cb56d",
        "after": "2afaaaf4f9b477c491c23afceffc62da1fa041d589120f2a26978b760f5e2c2c",
        "changes": (
            ("from ...utils import math as math_utils\n", "from ...utils import math as math_utils\nfrom ...utils.device import torch_device_for_sim\n"),
            ("r = torch.empty(num_envs_ids, 3, device=self.device)", "r = torch.empty(num_envs_ids, 3, device=torch_device_for_sim(self.device))"),
            ("torch.tensor(ray_cast_range_list, device=self.device)", "torch.tensor(ray_cast_range_list, device=torch_device_for_sim(self.device))"),
            ("ranges[:, 0], ranges[:, 1], (num_envs_ids, 3), device=self.device", "ranges[:, 0], ranges[:, 1], (num_envs_ids, 3), device=torch_device_for_sim(self.device)"),
            ("self.cfg.pattern_cfg.func(self.cfg.pattern_cfg, self._device)", "self.cfg.pattern_cfg.func(self.cfg.pattern_cfg, torch_device_for_sim(self._device))"),
            ("torch.tensor(list(self.cfg.offset.pos), device=self._device)", "torch.tensor(list(self.cfg.offset.pos), device=torch_device_for_sim(self._device))"),
            ("torch.tensor(list(self.cfg.offset.rot), device=self._device)", "torch.tensor(list(self.cfg.offset.rot), device=torch_device_for_sim(self._device))"),
            ("ProxyArray(wp.from_torch(ray_starts_torch, dtype=wp.vec3f))", "ProxyArray(wp.from_torch(ray_starts_torch, dtype=wp.vec3f).to(self._device))"),
            ("ProxyArray(wp.from_torch(ray_directions_torch, dtype=wp.vec3f))", "ProxyArray(wp.from_torch(ray_directions_torch, dtype=wp.vec3f).to(self._device))"),
        ),
    },
    {
        "path": "source/isaaclab/isaaclab/utils/math.py",
        "before": "be896b1734900f5ed5751de75a8ad517f131358934f5247968bd5f905ca9cd47",
        "after": "5fc27d0a261ae10851ec7acec6496ac8dec384c740631fd55729b02acd5de489",
        "changes": (
            ("import torch.nn.functional\n", "import torch.nn.functional\n\nfrom .device import torch_device_for_sim\n"),
            ("return torch.rand(*size, device=device) * (upper - lower) + lower", "return torch.rand(*size, device=torch_device_for_sim(str(device))) * (upper - lower) + lower"),
            ("    device = torch.device(device)\n    if device.type == \"cuda\"", "    device = torch.device(torch_device_for_sim(str(device)))\n    if device.type == \"cuda\""),
        ),
    },
    {
        "path": "source/isaaclab/isaaclab/utils/warp/proxy_array.py",
        "before": "9dbaf78e15548b4b7043ba54c0ab30efe4a9b53c49dcee1496d04c9042448ee4",
        "after": "3d34976fd8005e21f6a8062bd72bbb70d66611e6c082687b319cf26e35db5f22",
        "changes": ((
            "        if self._torch_cache is None:\n            self._torch_cache = wp.to_torch(self._warp)\n",
            "        # A cached CPU tensor still needs a handoff barrier after each Metal launch.\n"
            "        if getattr(self._warp.device, \"is_metal\", False):\n"
            "            wp.synchronize_device(self._warp.device)\n"
            "        if self._torch_cache is None:\n            self._torch_cache = wp.to_torch(self._warp)\n",
        ),),
    },
    {
        "path": "source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/g1/flat_env_cfg.py",
        "before": "94939822f944707ef7961613e0e54ba563fc047d92386900922bb39db3559df5",
        "after": "ea680d547428fd11210febc43eb2f903073b8c757644eab87396edb7a94dfc94",
        "changes": ((
            "        newton_mjwarp.solver_cfg.nconmax = 10\n",
            "        newton_mjwarp.solver_cfg.nconmax = 10\n"
            "        if self.sim.device.startswith(\"metal\"):\n"
            "            # Use the supported GPU contact path and room for whole-body contacts.\n"
            "            newton_mjwarp.solver_cfg.use_mujoco_contacts = True\n"
            "            newton_mjwarp.collision_cfg = None\n"
            "            newton_mjwarp.solver_cfg.njmax = 300\n"
            "            newton_mjwarp.solver_cfg.nconmax = 300\n",
        ),),
    },
)


def sha256(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def patched_bytes(data: bytes, repair: dict) -> bytes:
    source = data.decode("utf-8")
    for old, new in repair["changes"]:
        if source.count(old) != 1:
            raise ValueError("Repair does not match the supported source: " + repair["path"])
        source = source.replace(old, new, 1)
    result = source.encode("utf-8")
    if sha256(result) != repair["after"]:
        raise ValueError("Repair output checksum mismatch: " + repair["path"])
    compile(source, repair["path"], "exec")
    return result


def atomic_write(path: Path, data: bytes, mode: int) -> None:
    """Stage beside the target, preserving its file permissions, then replace it."""
    temporary = None
    try:
        with tempfile.NamedTemporaryFile(prefix=".simoji-repair-", dir=path.parent, delete=False) as stream:
            temporary = Path(stream.name)
            stream.write(data)
            stream.flush()
            os.fsync(stream.fileno())
            os.fchmod(stream.fileno(), mode)
        os.replace(temporary, path)
    finally:
        if temporary is not None:
            temporary.unlink(missing_ok=True)


def repair_sdk(sdk: Path, backup_root: Path | None = None) -> dict:
    sdk = sdk.expanduser().resolve()
    pair_path = sdk / "SimojiPairRelease.json"
    if not pair_path.is_file() or json.loads(pair_path.read_text()) != PAIR:
        raise ValueError("Expected the supported Simoji dev4 Isaac Lab package at " + str(sdk))

    pending = []
    already = []
    # Preflight every target before creating backups or modifying any source.
    for repair in REPAIRS:
        path = sdk / repair["path"]
        if not path.is_file() or path.resolve() != path:
            raise ValueError("Expected a regular source file without symlinks: " + str(path))
        original = path.read_bytes()
        digest = sha256(original)
        if digest == repair["after"]:
            already.append(repair["path"])
            continue
        if digest != repair["before"]:
            raise ValueError("Source differs from the supported release; left unchanged: " + str(path))
        pending.append((repair, path, original, patched_bytes(original, repair), stat.S_IMODE(path.stat().st_mode)))
    if not pending:
        return {"status": "already_repaired", "sdk": str(sdk), "updated": [], "already_repaired": already}

    backup_root = (backup_root or Path.home() / "SimojiBackups").expanduser().resolve()
    backup_root.mkdir(parents=True, exist_ok=True)
    stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S-%f")
    backup = backup_root / ("isaaclab-metal-repair-" + stamp)
    backup.mkdir(mode=0o700)
    for repair, _, original, _, mode in pending:
        copy = backup / repair["path"]
        copy.parent.mkdir(parents=True, exist_ok=True)
        copy.write_bytes(original)
        copy.chmod(mode)
    receipt = {
        "sdk": str(sdk), "pair": PAIR, "backup": str(backup),
        "files": [{"path": item[0]["path"], "before": item[0]["before"], "after": item[0]["after"]} for item in pending],
        "status": "backed_up",
    }
    receipt_path = backup / "repair.json"
    receipt_path.write_text(json.dumps(receipt, indent=2) + "\n")
    changed = []
    try:
        for repair, path, original, replacement, mode in pending:
            if path.read_bytes() != original:
                raise ValueError("Source changed while repairing; stopping: " + str(path))
            atomic_write(path, replacement, mode)
            changed.append((path, original, mode))
    except Exception:
        rollback_errors = []
        for path, original, mode in reversed(changed):
            try:
                atomic_write(path, original, mode)
            except Exception as error:
                rollback_errors.append(str(path) + ": " + str(error))
        receipt["status"] = "rollback_failed" if rollback_errors else "rolled_back"
        receipt["rollback_errors"] = rollback_errors
        receipt_path.write_text(json.dumps(receipt, indent=2) + "\n")
        if rollback_errors:
            raise RuntimeError("Restore these source files from " + str(backup) + ": " + "; ".join(rollback_errors))
        raise
    receipt["status"] = "repaired"
    receipt_path.write_text(json.dumps(receipt, indent=2) + "\n")
    return {"status": "repaired", "sdk": str(sdk), "updated": [item[0]["path"] for item in pending],
            "already_repaired": already, "backup": str(backup)}


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--sdk", type=Path, default=Path.home() / DEFAULT_SDK, help="Installed Isaac Lab source folder")
    args = parser.parse_args()
    try:
        result = repair_sdk(args.sdk)
    except (OSError, ValueError, RuntimeError) as error:
        parser.exit(1, "Repair stopped: " + str(error) + "\n")
    print(json.dumps(result, indent=2))
    print("Metal source repair is ready. Restart your Isaac Lab command in Terminal.")


if __name__ == "__main__":
    main()
