import subprocess
import sys
import os
import importlib.util

def is_package_installed(package_name):
    if package_name == 'pywin32':
        try:
            import win32api # type: ignore
            return True
        except ImportError:
            return False
    return importlib.util.find_spec(package_name) is not None

def install(package):
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", package])
    except subprocess.CalledProcessError:
        print(f"Failed to install {package}")

# List of required packages
packages = ['requests', 'winshell', 'pywin32', 'openpyxl']

# Check if any package needs to be installed
needs_installation = False
for package in packages:
    if not is_package_installed(package):
        print(f"Need to install {package}")
        needs_installation = True
        install(package)

if needs_installation:
    print("Restarting script to use newly installed packages...")
    python = sys.executable
    os.execl(python, python, *sys.argv)
else:
    print("All required packages are already installed.")

# The rest of your script starts here
import json
import requests
import winshell
from win32com.client import Dispatch

# ... (rest of your original script)

FileListURL = "http://reader.podlecki.pl/converter/default/fileList.json"
response = requests.get(FileListURL)
files = json.loads(response.content)

main_dir = 'c:/Allflex/Reader'

try:
    os.makedirs(main_dir)
except FileExistsError:
    pass

def crawler(dic, path = ''):
    path+='/'
    for key, value in dic.items():
        if type(value) != str:
            try:
                os.makedirs(main_dir+path+key)
            except FileExistsError:
                pass
            if value:
                crawler(value, path + key)
        else:
            tmpURL = filesURL + path + value
            response = requests.get(tmpURL)
            open(main_dir + path + '/' + key, "wb").write(response.content)


filesURL = "http://reader.podlecki.pl/converter/default"
crawler(files['folders'])
  
### Destctop shortcut creation ###  
desktop = winshell.desktop()

path = os.path.join(desktop, "AWR & APR - Database Update.lnk")
target = r"C:\Allflex\Reader\START.cmd"
wDir = r"C:\Allflex\Reader"
icon = r"C:\Allflex\Reader\icons\logo.ico"

shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.WorkingDirectory = wDir
shortcut.IconLocation = icon
shortcut.save()
exit()


