import sys
import subprocess
subprocess.check_call([sys.executable] + "-m pip install requests bs4".split(' '))

import requests
from pathlib import Path
from bs4 import BeautifulSoup
from urllib.parse import unquote

def download_directory(url, local_path:Path):
    response = requests.get(url)
    if response.status_code != 200:
        return -1

    for a in BeautifulSoup(response.text, "html.parser").find_all("a"):
        name_raw:str = a['href']
        name = unquote(name_raw)
        if name in ('.env', 'Dashboard.py', '../'): continue

        full_url = url + name
        full_local = local_path / name

        if name.endswith("/"):
            full_local.mkdir(parents=True, exist_ok=True)
            download_directory(full_url, full_local)
        else:
            full_local.parent.mkdir(parents=True, exist_ok=True)
            r = requests.get(full_url)
            if r.status_code == 200:
                with open(full_local, "wb") as f:
                    f.write(r.content)
    return 1

def sync_folder(FOLDER:Path, SERVER_URL):
    FOLDER.mkdir(parents=True, exist_ok=True)
    if int(download_directory(SERVER_URL, FOLDER)) < 0:
        raise ValueError("Invalid response from file server")
    
sync_folder(Path(__file__.rsplit("\\", 1)[0])/'DashBoard', r"https://mudaeapps.ddns.net/apps/DashBoard/")