import requests
import csv

trefle_token = 'token=usr-W4tH6OdX4jq_RqNot6aLJAW95Vr6ErAHLMesrL3WdG4'

with open('plants_biblical.csv', newline='') as plants_csv:
    reader = csv.reader(plants_csv)
    for row in reader:

        genus = row[0]
        epithet = row[1]
       
        request_url = 'https://trefle.io/api/v1/plants/search?'+ trefle_token + '&q='+genus+'%20'+epithet

        
        try:
            response = requests.get(request_url)

            response.raise_for_status()
            data = response.json()
            species_id = data['data'][0]['id']
                   

            species_request = "https://trefle.io/api/v1/plants/" + str(species_id) +'?'+ trefle_token
            
            try: 
                response = requests.get(species_request)
                response.raise_for_status()
                data = response.json()
                
                main_species = data['data']['main_species']
                
                
                distribution = main_species['distribution']['native']

                for locale in distribution: 
                    if locale == 'New York':
                        native_to_ny = True
                        print('This species is native to NY')
                    else:
                        native_to_ny = False
                
              
                    
                

                print(main_species['common_name'])

            except requests.exceptions.HTTPError as e:
                if e.response.status_code == 400:
                    print(f"404 Plant Not Found: {e}")
                    print(f"Response content: {e.response.text}")
                else:
                    print(f"Other HTTP Error: {e}")
            except Exception as e: 
                print(e)

            
        
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 404:
                print(f"404 Plant Not Found: {e}")
                print(f"Response content: {e.response.text}")
            else:
                print(f"Other HTTP Error: {e}")
        except Exception as e: 
             print("An unexpected error occurred: {e}")
            
            



       