"""Install verified portable tools in the si user's own versioned directory."""
import hashlib
import json
import os
from pathlib import Path
import secrets
import shutil
import tarfile

STAGE = Path.home() / ".local/share/contextra-offline-prep/20260928-r01"
PREFIX = Path.home() / ".local/opt/contextra-offline/20260928-r01"


def digest(path):
    result = hashlib.sha256()
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(1024**2), b""):
            result.update(block)
    return result.hexdigest()


def main():
    if os.geteuid() == 0:
        raise RuntimeError("Install as si, not root")
    os.umask(0o077)
    manifest = json.loads((STAGE / "assets-manifest.json").read_text())
    if PREFIX.exists() or (Path.home() / ".local/bin/ct-llm").exists():
        raise RuntimeError("Existing installation requires review; no overwrite")
    if shutil.disk_usage(Path.home()).free < 18 * 1024**3:
        raise RuntimeError("Insufficient filesystem reserve")
    for asset in manifest["assets"]:
        path = STAGE / "downloads" / asset["name"]
        if path.stat().st_size != asset["size_bytes"] or digest(path) != asset["sha256"]:
            raise RuntimeError("Asset mismatch: " + asset["name"])
    PREFIX.mkdir(parents=True)
    variants = {
        "gpu": "llama-b11146-bin-ubuntu-cuda-12.8-x64.tar.gz",
        "cuda-runtime": "cudart-llama-b11146-bin-ubuntu-cuda-12.8-x64.tar.gz",
        "cpu": "llama-b11146-bin-ubuntu-x64.tar.gz",
        "opencode": "opencode-linux-x64.tar.gz",
    }
    for name, archive in variants.items():
        destination = PREFIX / name
        destination.mkdir()
        with tarfile.open(STAGE / "downloads" / archive) as source:
            source.extractall(destination, filter="data")
    model = Path.home() / ".cache/huggingface/hub/models--unsloth--Qwen3.8-27B-GGUF/snapshots/4ca720788d1e01f1bff70c033e0d0028fd02e502/Qwen3.8-27B-UD-Q4_K_XL.gguf"
    if not model.is_file() or model.stat().st_size != 17559178144:
        raise RuntimeError("Existing model identity/size changed")
    config = dict(schema=1, model=str(model), context=16384, threads=8,
                  port=18080, alias="icerti-qwen", gpu_idle_max_mib=2048)
    (PREFIX / "config.json").write_text(json.dumps(config, indent=2))
    (PREFIX / "api-key").write_text(secrets.token_urlsafe(32) + "\n")
    for name in ("ct_llm.py", "system.ko.txt"):
        shutil.copy2(STAGE / name, PREFIX / name)
    bindir = Path.home() / ".local/bin"
    bindir.mkdir(exist_ok=True)
    shutil.copy2(STAGE / "ct-llm", bindir / "ct-llm")
    (bindir / "ct-llm").chmod(0o700)
    print(json.dumps(dict(status="INSTALLED_NOT_STARTED", prefix=str(PREFIX),
                          model_downloaded=False, autostart=False, api_key_printed=False)))


if __name__ == "__main__":
    main()
