"""
This script downloads the raw, combined csv files from an online storage bucket
"""
import configparser
import json
from pathlib import Path
import os
from google.cloud import storage


def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The ID of your GCS object
    # source_blob_name = "storage-object-name"

    # The path to which the file should be downloaded
    # destination_file_name = "local/path/to/file"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)

    # Construct a client side representation of a blob.
    # Note `Bucket.blob` differs from `Bucket.get_blob` as it doesn't retrieve
    # any content from Google Cloud Storage. As we don't need additional data,
    # using `Bucket.blob` is preferred here.
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)

    print(
        f"Downloaded storage object {source_blob_name} from bucket {bucket_name} to local file {destination_file_name}."
    )


# Set env config for accessing gcloud
path_to_creds = Path("creds/makingtextcount-8782aaac74a4.json")
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = str(path_to_creds)

config = configparser.ConfigParser()
config.read('config.ini')
paper_list = json.loads(config.get("papers", "paper_list"))
out_path = Path("data/raw")

for paper in paper_list:
    download_blob("makingtextcount",
                  f"raw/{paper}.csv",
                  Path(out_path/f"{paper}.csv"))
