import os
import subprocess
import urllib
import _winreg

# -----------------------------------
# CONFIG SECTION – REPLACE THE URLS
# -----------------------------------
URL_VC86  = "https://script-downloads.itarian.com/BlueBeam_Revu/vc_redist.x86.exe"
URL_VC64  = "https://script-downloads.itarian.com/BlueBeam_Revu/vc_redist.x64.exe"
URL_DOT48 = "https://script-downloads.itarian.com/BlueBeam_Revu/ndp48-x86-x64-allos-enu.exe"

URL_REVU  = "https://script-downloads.itarian.com/BlueBeam_Revu/BluebeamRevu_x64_21.msi"
URL_OCR   = "https://script-downloads.itarian.com/BlueBeam_Revu/BluebeamOCR_x64_21.msi"

DOWNLOAD_DIR = "C:\\BluebeamInstall"
if not os.path.exists(DOWNLOAD_DIR):
    os.makedirs(DOWNLOAD_DIR)


def download(url, path):
    print("Downloading: %s" % url)
    try:
        urllib.urlretrieve(url, path)
        print("Saved -> %s" % path)
    except Exception as e:
        print("Download failed: %s" % e)


def is_dotnet48_installed():
    try:
        key = _winreg.OpenKey(
            _winreg.HKEY_LOCAL_MACHINE,
            r"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full",
            0,
            _winreg.KEY_READ
        )
        release, _ = _winreg.QueryValueEx(key, "Release")
        return release >= 528040
    except:
        return False

def is_vcredist_installed(arch):
    # arch must be "x86" or "x64"
    reg_path = r"SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\%s" % arch
    try:
        key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, reg_path, 0, _winreg.KEY_READ)
        installed, _ = _winreg.QueryValueEx(key, "Installed")
        return installed == 1
    except:
        return False


def run_installer(cmd):
    print("Running: %s" % cmd)
    try:
        proc = subprocess.Popen(cmd, shell=True)
        proc.wait()
        print("Exit code: %d" % proc.returncode)
        return proc.returncode
    except Exception as e:
        print("Installer failed: %s" % e)
        return 1


file_vc86  = os.path.join(DOWNLOAD_DIR, "VC_redist.x86.exe")
file_vc64  = os.path.join(DOWNLOAD_DIR, "VC_redist.x64.exe")
file_dot48 = os.path.join(DOWNLOAD_DIR, "dotnet48.exe")
file_revu  = os.path.join(DOWNLOAD_DIR, "BluebeamRevu.msi")
file_ocr   = os.path.join(DOWNLOAD_DIR, "BluebeamOCR.msi")

download(URL_VC86,  file_vc86)
download(URL_VC64,  file_vc64)
download(URL_DOT48, file_dot48)
download(URL_REVU,  file_revu)
download(URL_OCR,   file_ocr)

# -------------------------------
# Install prerequisites
# -------------------------------

# .NET Framework 4.8
if not is_dotnet48_installed():
    print(".NET 4.8 missing – installing...")
    run_installer('"%s" /quiet /norestart' % file_dot48)
else:
    print(".NET 4.8 already installed.")

# Visual C++ x64
if not is_vcredist_installed("x64"):
    print("Visual C++ 2015–2022 x64 missing – installing...")
    run_installer('"%s" /install /quiet /norestart' % file_vc64)
else:
    print("Visual C++ x64 already installed.")

# Visual C++ x86
if not is_vcredist_installed("x86"):
    print("Visual C++ 2015–2022 x86 missing – installing...")
    run_installer('"%s" /install /quiet /norestart' % file_vc86)
else:
    print("Visual C++ x86 already installed.")


print("Installing Bluebeam Revu...")
run_installer('msiexec /i "%s" /qn /norestart' % file_revu)

print("Installing Bluebeam OCR...")
run_installer('msiexec /i "%s" /qn /norestart' % file_ocr)

print("All operations completed.")
