import json
import os
import urllib.request
from urllib.error import HTTPError, URLError

from edpconfigprovider import ConfigProvider
from edpconfigprovider.exceptions import NoConfigurationException


class AwsAppconfigAgentProvider(ConfigProvider):
    def __init__(
        self,
        application_name: str,
        profile_name: str,
        environment_name: str,
    ):
        self.application_name = application_name
        self.profile_name = profile_name
        self.environment_name = environment_name
        self.port = os.environ.get("AWS_APPCONFIG_EXTENSION_HTTP_PORT", "2772")

    def get_latest_config_version(self):
        try:
            url = f"http://localhost:{self.port}/applications/{self.application_name}/environments/{self.environment_name}/configurations/{self.profile_name}"  # noqa
            return json.loads(urllib.request.urlopen(url).read())
        except (HTTPError, URLError):
            raise NoConfigurationException(
                configuration_name=f"{self.application_name}/{self.environment_name}/{self.profile_name}"
            )

    def get_configuration(self) -> dict:
        return self.get_latest_config_version()
