"""
Google Drive folder downloader using gdown.
"""

import os
import gdown

from ktunotes.ui import show_success, show_error, show_info


def download_folder(url: str, subject_code: str) -> str:
    """
    Download a Google Drive folder to ~/ktunotes/<subject_code>/

    Args:
        url: Google Drive folder URL
        subject_code: Subject code used as the directory name

    Returns:
        Path to the download directory
    """
    dest = os.path.join(os.path.expanduser('~'), 'ktunotes', subject_code.lower())
    os.makedirs(dest, exist_ok=True)

    show_info(f"Downloading to ~/{os.path.relpath(dest, os.path.expanduser('~'))}/")
    print()

    try:
        gdown.download_folder(url, output=dest, quiet=False)
        print()
        show_success(f"Saved to {dest}")
    except Exception as e:
        print()
        show_error(f"Download failed: {e}")
        show_info("Will open in browser instead.")
        return dest

    return dest
