import httpx
from typing import Optional
from common import logging

logger = logging.get_logger(__name__)


class RedditPublisher:
    BASE_URL = "https://oauth.reddit.com"

    @staticmethod
    async def post_link(
        access_token: str,
        subreddit: str,
        clip_url: str,
        caption: str,
        *,
        flair_id: Optional[str] = None,
        user_agent: str = "TLDRPublisher/0.1 (by u/your_reddit_username)",
    ) -> dict:
        form = {
            "sr": subreddit,
            "kind": "link",
            "title": caption,
            "url": clip_url,
            "resubmit": "true",
            "api_type": "json",
        }
        if flair_id:
            form["flair_id"] = flair_id
        headers = {
            "Authorization": f"Bearer {access_token}",
            "User-Agent": user_agent,
            "Content-Type": "application/x-www-form-urlencoded",
        }
        url = f"{RedditPublisher.BASE_URL}/api/submit"
        async with httpx.AsyncClient(timeout=30.0) as client:
            try:
                resp = await client.post(url, data=form, headers=headers)
                resp.raise_for_status()
                data = resp.json()
                errors = data.get("json", {}).get("errors", [])
                if errors:
                    logger.error(f"[Reddit] Submit errors: {errors}")
                    raise RuntimeError(f"Reddit submit failed: {errors}")
                post_data = data.get("json", {}).get("data", {})
                permalink = post_data.get("url") or post_data.get("permalink")
                name = post_data.get("name")
                logger.info(
                    f"[Reddit] Link post created in r/{subreddit}: {permalink} ({name})"
                )
                return {
                    "subreddit": subreddit,
                    "name": name,
                    "permalink": permalink,
                    "raw": data,
                }
            except httpx.HTTPStatusError as e:
                logger.error(
                    f"[Reddit] HTTP {e.response.status_code}: {e.response.text}"
                )
                raise
            except Exception as e:
                logger.error(f"[Reddit] Unexpected error: {e}")
                raise
