"""Regenerate the Android engine lock the app installs on first run.

Writes Android/runtime/requirements-android.lock: hash-pinned wheels for the
same packages the Windows runtime installs (Desktop/runtime/requirements-windows.lock,
pruned to what GeoCeptor imports), installed with --no-deps. Packages with C or
Rust code have no Android wheels on PyPI; build them with build_wheels.sh and
pass their folder here, so their hashes are pinned too. Requires uv.

    python3 Android/scripts/lock_android.py path/to/android-wheels
"""
from pathlib import Path
import hashlib
import json
import re
import subprocess
import sys
import tempfile

ANDROID = Path(__file__).resolve().parent.parent
REPOSITORY = ANDROID.parent
WINDOWS_LOCK = REPOSITORY / "Desktop" / "runtime" / "requirements-windows.lock"
OUTPUT = ANDROID / "runtime" / "requirements-android.lock"
MANIFEST = ANDROID / "runtime" / "python-android.json"


def python_minor() -> str:
    """"3.14" for the pinned 3.14.8: the wheels must be built and locked for the Python the app installs."""
    return ".".join(json.loads(MANIFEST.read_text(encoding="utf-8"))["version"].split(".")[:2])

# Not installed on Android:
SKIPPED = {
    "colorama", "pyreadline3", "pywin32",  # Windows only
    "psutil",  # no Android build; Python/utils/android_compat.py stands in
    "backports-zstd",  # in the standard library from Python 3.14
}


def normalized(name):
    return re.sub(r"[-_.]+", "-", name).lower()


def pins(lock_text):
    return [line.split(" ")[0] for line in lock_text.splitlines() if re.match(r"^[A-Za-z0-9_.-]+==", line)]


def selection(lock_text):
    return [pin for pin in pins(lock_text) if normalized(pin.split("==")[0]) not in SKIPPED]


def local_wheels(wheels, name, version):
    return [wheel for wheel in sorted(wheels.glob("*.whl"))
            if normalized(wheel.name.split("-")[0]) == normalized(name) and wheel.name.split("-")[1] == version]


def pin_local_wheels(lock_text, wheels):
    """Pin packages built here to their files' SHA-256. uv leaves such wheels
    unhashed, or reuses a cached hash after a rebuild."""
    entries = re.split(r"\n(?=[A-Za-z0-9_.-]+==)", lock_text.strip())
    pinned = []
    for entry in entries:
        name, version = entry.split(" ")[0].split("\n")[0].split("==")
        files = local_wheels(wheels, name, version)
        if files:
            hashes = [f"    --hash=sha256:{hashlib.sha256(wheel.read_bytes()).hexdigest()}" for wheel in files]
            entry = " \\\n".join([f"{name}=={version}"] + hashes)
        elif "--hash=" not in entry:
            raise SystemExit(f"{name}=={version} has no hash and no Android wheel in {wheels}")
        pinned.append(entry)
    return "\n".join(pinned) + "\n"


def main(wheels):
    chosen = selection(WINDOWS_LOCK.read_text(encoding="utf-8"))
    with tempfile.TemporaryDirectory() as scratch:
        requirements = Path(scratch) / "selection.in"
        requirements.write_text("\n".join(chosen) + "\n", encoding="utf-8")
        subprocess.run(
            ["uv", "pip", "compile", requirements, "--python-platform", "aarch64-linux-android",
             "--python-version", python_minor(), "--generate-hashes", "--only-binary", ":all:", "--no-deps",
             "--find-links", wheels, "--no-header", "--no-annotate", "--no-cache", "--quiet", "-o", OUTPUT],
            check=True,
        )
    OUTPUT.write_text(pin_local_wheels(OUTPUT.read_text(encoding="utf-8"), wheels), encoding="utf-8")
    print(f"Locked {len(chosen)} packages in {OUTPUT}")


if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise SystemExit(__doc__)
    main(Path(sys.argv[1]).resolve())
