# GUIBRUSHR/scripts/downloader.py
import zipfile
from pathlib import Path
import gdown

FILE_ID = "1eeEjNf4My6pJ8VMXKZppHSX6SWnycXbV"
SENTINEL = "GUIBRUSHR/Files/Configuration_Yaml/general.yaml"


def _get_base_path() -> Path:
    # __file__ = site-packages/GUIBRUSHR/scripts/downloader.py
    # .parent        = site-packages/GUIBRUSHR/scripts/
    # .parent.parent = site-packages/GUIBRUSHR/
    # .parent.parent.parent = site-packages/  ← base_path corretta
    return Path(__file__).parent.parent.parent.resolve()


def download_files(base_path: Path = None) -> None:
    if base_path is None:
        base_path = _get_base_path()

    if (base_path / SENTINEL).exists():
        return

    print("First run: downloading GUIBRUSHR data files (~160 MB)...")
    zip_dest = base_path / "GUIBRUSHR" / "Files" / "_data.zip"
    zip_dest.parent.mkdir(parents=True, exist_ok=True)

    gdown.download(id=FILE_ID, output=str(zip_dest), quiet=False)

    print("Extracting...")
    with zipfile.ZipFile(zip_dest, "r") as z:
        z.extractall(base_path)

    zip_dest.unlink()
    print("✓ Data files ready.")


def download_files_cli():
    """Entry point per il comando guibrushr-download"""
    download_files()


if __name__ == "__main__":
    download_files()
