# -*- coding: utf-8 -*-
"""Attempt 3D Gaussian Splatting setup to document the blocker.

Downloads the diff-gaussian-rasterization CUDA-extension source (the hard
dependency of the official gaussian-splatting repo) and tries to build it.
The build needs MSVC (cl.exe) + CMake + CUDA; without MSVC it fails.
"""
import os, sys, tarfile, io, urllib.request, subprocess

URL = "https://github.com/graphdeco-inria/diff-gaussian-rasterization/archive/refs/heads/master.tar.gz"
DEST = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dgr.tar.gz")
EXTRACT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "diff-gaussian-rasterization-master")

def main():
    if not os.path.exists(DEST):
        print("downloading diff-gaussian-rasterization tarball ...")
        req = urllib.request.Request(URL, headers={"User-Agent": "Mozilla/5.0"})
        with urllib.request.urlopen(req, timeout=120) as r, open(DEST, "wb") as f:
            f.write(r.read())
        print("downloaded", os.path.getsize(DEST), "bytes")
    if not os.path.exists(EXTRACT):
        print("extracting ...")
        with tarfile.open(DEST, "r:gz") as tf:
            tf.extractall(os.path.dirname(EXTRACT))
    print("attempting build (will fail without MSVC) ...")
    r = subprocess.run([sys.executable, "-m", "pip", "install", "--no-cache-dir", EXTRACT],
                       capture_output=True, text=True, timeout=300)
    tail = (r.stdout + r.stderr).splitlines()[-25:]
    print("\n".join(tail))
    print("exit code:", r.returncode)


if __name__ == "__main__":
    main()
