import requests
import json
from pathlib import Path
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from msrest.authentication import CognitiveServicesCredentials

class AzureCVClient():
    def __init__(self):
        self.endpoint, self.key = self._get_credentials()
        self.client = ComputerVisionClient(
            endpoint=self.endpoint,
            credentials=CognitiveServicesCredentials(subscription_key=self.key)
        )

    @staticmethod
    def _get_credentials():
        azure_cred_path = Path(__file__).parent/"creds"/"azure_credentials.json"
        with open(azure_cred_path, "r") as azure_cred_file:
            creds = json.load(azure_cred_file)
            endpoint = creds["endpoint"]
            key = creds["key"]
            azure_cred_file.close()

        if endpoint is None or key is None:
            raise Exception("Failed to get endpoint/key for AzureCVClient")
        else:
            return endpoint, key

    def get_best_caption(self, img_url: str):
        analysis = self.client.describe_image(url=img_url)
        return analysis.captions[0].text