import praw
from typing import Optional, Dict, Any
from app.services.base_service import SocialMediaService


class RedditService(SocialMediaService):
    """
    Reddit API service using PRAW.
    Credentials:
      api_key    = Client ID
      secret_key = Client Secret
      extra      = JSON: {"username": "...", "password": "...", "subreddit": "...", "title": "..."}
    """
    platform_name = "reddit"

    def validate_credentials(self) -> bool:
        return bool(self.credentials.get("api_key") and self.credentials.get("secret_key"))

    def post(self, content: str, media_path: Optional[str] = None) -> Dict[str, Any]:
        import json

        client_id = self.credentials.get("api_key", "")
        client_secret = self.credentials.get("secret_key", "")
        extra_raw = self.credentials.get("extra", "{}")

        try:
            extra = json.loads(extra_raw) if extra_raw else {}
        except Exception:
            extra = {}

        username = extra.get("username", "")
        password = extra.get("password", "")
        subreddit_name = extra.get("subreddit", "test")
        post_title = extra.get("title", content[:100])

        if not all([client_id, client_secret, username, password]):
            return self._error("Missing Reddit credentials (client_id, client_secret, username, password)")

        try:
            reddit = praw.Reddit(
                client_id=client_id,
                client_secret=client_secret,
                username=username,
                password=password,
                user_agent=f"OneClickAutomation/1.0 by u/{username}",
            )

            subreddit = reddit.subreddit(subreddit_name)

            if media_path:
                submission = subreddit.submit_image(title=post_title, image_path=media_path)
            else:
                submission = subreddit.submit(title=post_title, selftext=content)

            return self._success(
                f"Posted to r/{subreddit_name} successfully",
                {"post_url": submission.url, "post_id": submission.id}
            )

        except praw.exceptions.PRAWException as e:
            return self._error(f"Reddit API error: {str(e)}")
        except Exception as e:
            return self._error(f"Reddit connection error: {str(e)}")
