import dropbox
from pathlib import Path
import os
from dotenv import load_dotenv

load_dotenv()

ACCESS_TOKEN = os.getenv('DROPBOX_ACCESS_TOKEN')

dbx = dropbox.Dropbox(ACCESS_TOKEN)

def download_file_from_shared_link(shared_link, local_path):
    try:
        # Remove any query parameters from the URL, Dropbox API doesn't need them.
        shared_link = shared_link.split('?')[0]
        
        # Use the Dropbox API to download the file from a shared link directly into the local file.
        _, res = dbx.sharing_get_shared_link_file(url=shared_link)
        
        with open(local_path, "wb") as f:
            f.write(res.content)
        
        print(f"File downloaded successfully to {local_path}")
    except dropbox.exceptions.ApiError as err:
        print(f"Dropbox API error: {err}")

# Example usage
#dropbox_shared_link = "https://www.dropbox.com/scl/fi/fem332616ru9m9dnasjrx/3175_001.pdf"
dropbox_shared_link = "https://www.dropbox.com/scl/fi/3hqlmxhlakuo1w9fs6lbm/AssurX-Proposal-NDOT.pdf"
local_file_path = "./downloaded_files_from_dropbox/AssurX-Proposal-NDOT.pdf"

#https://www.dropbox.com/scl/fi/3hqlmxhlakuo1w9fs6lbm/AssurX-Proposal-NDOT.pdf?rlkey=okggqsmm9m2r2xcpoiiflwblx&dl=0

# Ensure local path directory exists
Path(local_file_path).parent.mkdir(parents=True, exist_ok=True)

# Call the function to download the file from the shared link
download_file_from_shared_link(dropbox_shared_link, local_file_path)

#https://www.dropbox.com/oauth2/authorize?client_id=g13imu0lpjot6ey&response_type=code&redirect_uri=http://localhost:8000

#http://localhost:8000/?code=skiShx07TJAAAAAAAAAAFtXFfFEWvgZaxxR2o3R_DbU