"""Reddit API client wrapper with PRAW."""

import os
from typing import ClassVar

import praw
from dotenv import load_dotenv

# Load .env file if present
load_dotenv()


class RedditClientError(Exception):
    """Error related to Reddit client initialization."""


class RedditClient:
    """Singleton wrapper for PRAW Reddit instance."""

    _instance: ClassVar[praw.Reddit | None] = None
    _required_env_vars: ClassVar[list[str]] = [
        "REDDIT_CLIENT_ID",
        "REDDIT_CLIENT_SECRET",
        "REDDIT_USERNAME",
        "REDDIT_PASSWORD",
        "REDDIT_USER_AGENT",
    ]

    @classmethod
    def get_instance(cls) -> praw.Reddit:
        """Get or create the authenticated Reddit instance.

        Returns:
            Authenticated praw.Reddit instance.

        Raises:
            RedditClientError: If required environment variables are missing
                or authentication fails.
        """
        if cls._instance is None:
            cls._validate_env()
            try:
                cls._instance = praw.Reddit(
                    client_id=os.getenv("REDDIT_CLIENT_ID"),
                    client_secret=os.getenv("REDDIT_CLIENT_SECRET"),
                    username=os.getenv("REDDIT_USERNAME"),
                    password=os.getenv("REDDIT_PASSWORD"),
                    user_agent=os.getenv("REDDIT_USER_AGENT"),
                )
                # Verify authentication by accessing user identity
                _ = cls._instance.user.me()
            except praw.exceptions.PRAWException as e:
                cls._instance = None
                msg = f"Failed to authenticate with Reddit: {e}"
                raise RedditClientError(msg) from e
        return cls._instance

    @classmethod
    def _validate_env(cls) -> None:
        """Validate that all required environment variables are set.

        Raises:
            RedditClientError: If any required variables are missing.
        """
        missing = [var for var in cls._required_env_vars if not os.getenv(var)]
        if missing:
            msg = (
                f"Missing required environment variables: {', '.join(missing)}. "
                f"Please set them in your .env file or environment."
            )
            raise RedditClientError(msg)

    @classmethod
    def reset(cls) -> None:
        """Reset the singleton instance. Useful for testing."""
        cls._instance = None


def get_reddit() -> praw.Reddit:
    """Convenience function to get the Reddit instance.

    Returns:
        Authenticated praw.Reddit instance.
    """
    return RedditClient.get_instance()
