import requests
import os
import json

# Get current working directory (where the script is run)
download_dir = os.getcwd()
glycan_list_file = os.path.join(download_dir, "glycan_list.json")  # JSON file

# Check that the glycan list exists
if not os.path.exists(glycan_list_file):
    print(f"Error: {glycan_list_file} not found.")
    exit(1)

# Load glycan IDs from JSON list
try:
    with open(glycan_list_file) as f:
        glycan_ids = json.load(f)
except json.JSONDecodeError as e:
    print(f"Error parsing JSON: {e}")
    exit(1)

if not glycan_ids:
    print("No glycan IDs found in the list.")
    exit(0)

# Download PDB files
for glycan_id in glycan_ids:
    url = f"https://glycoshape.org/api/pdb/{glycan_id}"
    output_file = os.path.join(download_dir, f"{glycan_id}.pdb")
    
    try:
        response = requests.get(url)
        response.raise_for_status()  # Raise error for bad HTTP status
        # Check if response has content
        if not response.content.strip():
            print(f"No PDB content for {glycan_id}")
            continue
        with open(output_file, "wb") as f_out:
            f_out.write(response.content)
        print(f"Downloaded {output_file}")
    except requests.exceptions.RequestException as e:
        print(f"Failed to download {glycan_id}: {e}")


