import json
from pathlib import Path
from typing import Any, Dict, Optional
from ..models import MediaItem
from .base import BaseResource

class ImagesResource(BaseResource):
    def upload(
        self,
        collection_id: str,
        file_path: str,
        external_metadata: Optional[Dict[str, Any]] = None,
    ) -> MediaItem:
        path = Path(file_path)
        with open(path, "rb") as f:
            files = {"file": (path.name, f)}
            data = {}
            if external_metadata:
                data["external_metadata"] = json.dumps(external_metadata)
            result = self._request(
                "POST",
                f"/api/v1/sdk/collections/{collection_id}/images",
                files=files,
                data=data,
            )
        return MediaItem(**result)

    def get(self, image_id: str) -> MediaItem:
        data = self._request("GET", f"/api/v1/sdk/images/{image_id}")
        return MediaItem(**data)

    def update_metadata(self, image_id: str, external_metadata: Dict[str, Any]) -> MediaItem:
        data = self._request(
            "PUT", f"/api/v1/sdk/images/{image_id}/metadata",
            json={"external_metadata": external_metadata},
        )
        return MediaItem(**data)

    def delete(self, image_id: str) -> dict:
        return self._request("DELETE", f"/api/v1/sdk/images/{image_id}")
