import requests
from typing import List, Dict, Any
from dotenv import load_dotenv
import os
from requests.auth import HTTPBasicAuth

# Load environment variables from .env file
load_dotenv()

def getBundle(url: str, search: str):
    headers = {
        'Accept': 'application/fhir+json',
        'Content-Type': 'application/fhir+json'
    }

    # Get configuration from environment variables
    mode = os.getenv('MODE')
    fhir_server = os.getenv('FHIR_SERVER_URL')

    if mode != 'testsever':
        username = os.getenv('FHIR_SERVER_USER')
        password = os.getenv('FHIR_SERVER_PW')

    
    if not fhir_server:
        raise ValueError("FHIR_SERVER_URL not found in environment variables")
    if (not username or not password) and mode != 'testserver':
        raise ValueError("FHIR_USERNAME and FHIR_SERVER_PW must be set in environment variables")
    
    # Setup basic authentication
    auth = HTTPBasicAuth(username, password)

    
    if url is not None:
        link = url + '?_format=json'
    else:
        link = fhir_server + search + '&_format=json'

    #print(link)

    if mode != 'testserver':
        response = requests.get(
            link,
            headers=headers,
            auth=auth
        )
    else:
        response = requests.get(
            link,
            headers=headers,
        )
    return response

def getPatientEverything(id: str):
    search = '/Patient/' + id +  '/$everything?'
    return getBundle(None, search)


# Example usage
if __name__ == "__main__":
    bundles = get_bundles(None)
    data = bundles.json()
    
    # Process the bundles
    for entry in data['entry']:
        print(f"{entry['fullUrl']}")
