#!/usr/bin/env python3
"""Apply / revert source patches on an installed vLLM package.

Each patch step lives in ``steps/<name>.py`` and returns a list of file
operations (see ``steps/_ops.py``). The runner applies them to the target
vLLM package directory, keeps a backup of every touched file, and can
restore that backup with ``--revert``.

Usage:
    python apply_patch.py --dry-run              # print the unified diff only
    python apply_patch.py                        # apply all steps
    python apply_patch.py --steps kimi_k31_nonuniform_experts
    python apply_patch.py --revert               # restore backed-up files
    python apply_patch.py --vllm-dir /path/to/site-packages/vllm ...

Without --vllm-dir the target is the ``vllm`` package found by the python
interpreter that runs this script (run it with the venv's python).
"""

from __future__ import annotations

import argparse
import difflib
import importlib
import importlib.util
import json
import re
import shutil
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))

from steps._ops import Copy, Edit  # noqa: E402

# Order matters: later steps may edit files that earlier steps created.
ALL_STEPS = [
    "kimi_k31_nonuniform_experts",
]

SUPPORTED_VLLM = "0.1.dev24216+g266e88c05"  # vllm/vllm-openai:kimi-k31
BACKUP_DIRNAME = ".nota_patch_backup"


def find_vllm_dir() -> Path:
    spec = importlib.util.find_spec("vllm")
    if spec is None or spec.origin is None:
        sys.exit("vllm not found; pass --vllm-dir or run with the venv python")
    return Path(spec.origin).parent


def read_vllm_version(vllm_dir: Path) -> str:
    # Read version without importing vllm (importing is slow and needs CUDA).
    for dist in vllm_dir.parent.glob("vllm-*.dist-info"):
        m = re.match(r"vllm-(.+)\.dist-info", dist.name)
        if m:
            return m.group(1)
    v = vllm_dir / "_version.py"
    if v.exists():
        m = re.search(r"version = .*?['\"]([^'\"]+)", v.read_text())
        if m:
            return m.group(1)
    return "unknown"


def render(ops, vllm_dir: Path) -> dict[str, tuple[str | None, str]]:
    """Return {relpath: (old_text or None, new_text)} after all ops."""
    state: dict[str, tuple[str | None, str]] = {}

    def current(rel: str) -> str:
        if rel in state:
            return state[rel][1]
        p = vllm_dir / rel
        if not p.exists():
            raise FileNotFoundError(f"{rel}: target file does not exist")
        return p.read_text()

    def original(rel: str) -> str | None:
        if rel in state:
            return state[rel][0]
        p = vllm_dir / rel
        return p.read_text() if p.exists() else None

    for op in ops:
        if isinstance(op, Copy):
            state[op.dst] = (original(op.dst), op.text)
        elif isinstance(op, Edit):
            text = current(op.path)
            n = text.count(op.old)
            if n != op.count:
                raise RuntimeError(
                    f"{op.path}: anchor found {n} times (expected {op.count}).\n"
                    f"  reason: {op.reason}\n  anchor:\n{op.old}"
                )
            state[op.path] = (original(op.path), text.replace(op.old, op.new))
        else:
            raise TypeError(op)
    return state


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--vllm-dir", type=Path)
    ap.add_argument("--steps", nargs="+", default=ALL_STEPS, choices=ALL_STEPS)
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--revert", action="store_true")
    ap.add_argument("--force", action="store_true", help="skip version check")
    ap.add_argument("--diff-out", type=Path, help="also write the diff here")
    args = ap.parse_args()

    vllm_dir = (args.vllm_dir or find_vllm_dir()).resolve()
    backup_dir = vllm_dir / BACKUP_DIRNAME
    manifest_path = backup_dir / "manifest.json"
    print(f"target vllm: {vllm_dir}")

    if args.revert:
        if not manifest_path.exists():
            sys.exit("no backup manifest; nothing to revert")
        manifest = json.loads(manifest_path.read_text())
        for rel, existed in manifest["files"].items():
            dst = vllm_dir / rel
            if existed:
                shutil.copy2(backup_dir / rel, dst)
                print(f"  restored {rel}")
            else:
                dst.unlink(missing_ok=True)
                print(f"  removed  {rel}")
        shutil.rmtree(backup_dir)
        return

    version = read_vllm_version(vllm_dir)
    print(f"vllm version: {version}")
    if version != SUPPORTED_VLLM and not args.force:
        sys.exit(f"this patch targets vllm {SUPPORTED_VLLM}; use --force to try")
    if manifest_path.exists():
        steps = json.loads(manifest_path.read_text())["steps"]
        sys.exit(f"already patched with steps {steps} (backup at {backup_dir}); "
                 "run --revert first")

    ops = []
    for name in args.steps:
        mod = importlib.import_module(f"steps.{name}")
        step_ops = mod.ops()
        print(f"step {name}: {len(step_ops)} ops - {mod.DESCRIPTION}")
        ops.extend(step_ops)

    state = render(ops, vllm_dir)

    diff = []
    for rel, (old, new) in state.items():
        diff.extend(
            difflib.unified_diff(
                (old or "").splitlines(keepends=True),
                new.splitlines(keepends=True),
                fromfile=f"a/vllm/{rel}" if old is not None else "/dev/null",
                tofile=f"b/vllm/{rel}",
            )
        )
    diff_text = "".join(diff)
    if args.diff_out:
        args.diff_out.write_text(diff_text)
        print(f"diff written to {args.diff_out}")
    if args.dry_run:
        print(diff_text)
        return

    files = {}
    for rel, (old, new) in state.items():
        dst = vllm_dir / rel
        files[rel] = old is not None
        if old is not None:
            (backup_dir / rel).parent.mkdir(parents=True, exist_ok=True)
            shutil.copy2(dst, backup_dir / rel)
        dst.parent.mkdir(parents=True, exist_ok=True)
        dst.write_text(new)
        print(f"  {'patched' if old is not None else 'created'} {rel}")
    manifest_path.parent.mkdir(parents=True, exist_ok=True)
    manifest_path.write_text(
        json.dumps({"steps": args.steps, "vllm": version, "files": files}, indent=2)
    )
    print(f"backup: {backup_dir}")


if __name__ == "__main__":
    main()
