from dotenv import load_dotenv
import os
import requests

class LibpostalService:

    def __init__(self):
        load_dotenv()
        self.libpostal_url = os.getenv("LIBPOSTAL_URL")

    def parse_address(self, address_string):
        if not self.libpostal_url:
            raise ValueError("LIBPOSTAL_URL is not set in environment variables.")

        url = f"{self.libpostal_url}/parse"
        print(url)
        params = {"address": address_string}
        try:
            response = requests.get(url, params=params)
            response.raise_for_status()  # Raise an exception for HTTP errors
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"Error parsing address: {e}")
            return None

    def expand_address(self, address_string):
        if not self.libpostal_url:
            raise ValueError("LIBPOSTAL_URL is not set in environment variables.")

        url = f"{self.libpostal_url}/expand"
        params = {"address": address_string}
        try:
            response = requests.get(url, params=params)
            response.raise_for_status()  # Raise an exception for HTTP errors
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"Error expanding address: {e}")
            return None
