import requests
from pathlib import Path


def download_pdf(year, date, url, dir=None):
    """Downloads a pdf from the given url and stores it in the sub-directory
    for the year in which the meeting occurred

    Args:
        year: Year in which the BOE meeting occurred
        date: Date on which BOE meeting occurred, with format YYYY-MM-DD
        url: Link to download the pdf of the minutes

    Returns:
        passed: Boolean value indicating if the download was successful
        message: Message describing the error or success of the download
        pdf_file: Path to downloaded file
    """
    # checks that url is valid
    try:
        response = requests.get(url)
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        error = f"An error occurred requesting {url}: {e}"
        return False, error, None

    # checks that the response is a pdf
    content_type = response.headers["content-type"]
    if "pdf" not in content_type:
        error = f"The content stored at {url} is not a pdf"
        return False, error, None

    # creates path to file
    if not dir:
        dir = Path.cwd() / "pdf_files"
    year_dir = dir / year
    pdf_name = date + ".pdf"
    pdf_file = year_dir / pdf_name

    # creates the year directory and writes the file to it
    try:
        year_dir.mkdir(parents=True, exist_ok=True)
        with open(pdf_file, "wb") as f:
            f.write(response.content)
    except TypeError as e:
        error = f"An error occurred with url {url}: {e}"
        return False, error, None

    message = f"Successfully saved pdf from {url}"
    return True, message, pdf_file