import httpx
from typing import Optional, Dict, Any
from app.services.base_service import SocialMediaService


class InstagramService(SocialMediaService):
    """
    Instagram Business API via Meta Graph API.
    Credentials:
      api_key = Page Access Token
      extra   = Instagram Business Account ID
    """
    platform_name = "instagram"

    GRAPH_URL = "https://graph.facebook.com/v19.0"

    def validate_credentials(self) -> bool:
        return bool(self.credentials.get("api_key") and self.credentials.get("extra"))

    def post(self, content: str, media_path: Optional[str] = None) -> Dict[str, Any]:
        access_token = self.credentials.get("api_key", "")
        ig_account_id = self.credentials.get("extra", "")

        if not access_token or not ig_account_id:
            return self._error("Missing Instagram access token or account ID")

        try:
            if media_path:
                # Step 1: Upload image to create a container
                with open(media_path, "rb") as img:
                    upload_resp = httpx.post(
                        f"{self.GRAPH_URL}/{ig_account_id}/media",
                        params={
                            "caption": content,
                            "access_token": access_token,
                        },
                        files={"image_url": img},
                        timeout=30,
                    )
                if upload_resp.status_code != 200:
                    return self._error(f"Instagram media upload failed: {upload_resp.text}")
                container_id = upload_resp.json().get("id")
            else:
                # Text-only posts require a placeholder image; use a note
                return self._error("Instagram requires an image. Please attach a photo.")

            # Step 2: Publish the container
            publish_resp = httpx.post(
                f"{self.GRAPH_URL}/{ig_account_id}/media_publish",
                params={"creation_id": container_id, "access_token": access_token},
                timeout=30,
            )

            if publish_resp.status_code == 200:
                return self._success("Posted to Instagram successfully", publish_resp.json())
            else:
                return self._error(f"Instagram publish error: {publish_resp.text}")

        except Exception as e:
            return self._error(f"Instagram connection error: {str(e)}")
