from typing import Any, Dict, Optional

import instalabel.client
from instalabel.client.models.annotation_data import AnnotationData
from instalabel.client.models.image_response import ImageResponse
from instalabel.config import INSTALABEL_CLIENT_CONFIGURATION as configuration


class Image:
    def __init__(self, image: ImageResponse):
        self.id = image.image_id
        self.project_id = image.project_id
        self.user_id = image.user_id
        self.filename = image.filename
        self.status = image.status
        self.annotations_count = image.annotations_count
        self.annotations = image.annotations
        self.created_at = image.created_at
        self.updated_at = image.updated_at
        self.presigned_url = image.presigned_url

    def refresh(self) -> bool:
        """Refresh image data from the server"""
        with instalabel.client.ApiClient(configuration) as api_client:
            api_instance = instalabel.client.ImagesApi(api_client)

            try:
                api_response = api_instance.get_image_api_v1_images_image_id_get(
                    image_id=self.id, project_id=self.project_id
                )
                self.__init__(api_response)
                return True
            except Exception as e:
                print(f"Exception when getting image: {e}")
                return False

    def get_annotations(self) -> AnnotationData:
        """Get image annotations"""
        return self.annotations

    def __str__(self):
        return (
            f"Image(ID: {self.id}, Filename: {self.filename}, Status: {self.status}, "
            f"Annotation Count: {self.annotations_count}, Created At: {self.created_at})"
        )
