"""
Posts resource for managing social media posts.
"""

from __future__ import annotations

from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any

from ..models import Post

if TYPE_CHECKING:
    from ..client.base import BaseClient


class PostsResource:
    """
    Resource for managing posts.

    Example:
        >>> client = Late(api_key="...")
        >>> posts = client.posts.list()
        >>> post = client.posts.create(
        ...     content="Hello!",
        ...     platforms=[{"platform": "twitter", "accountId": "..."}],
        ... )
    """

    _BASE_PATH = "/v1/posts"

    def __init__(self, client: "BaseClient") -> None:
        self._client = client

    def list(
        self,
        *,
        page: int = 1,
        limit: int = 10,
        status: str | None = None,
        platform: str | None = None,
        profile_id: str | None = None,
    ) -> dict[str, Any]:
        """List posts with optional filters."""
        params: dict[str, Any] = {"page": page, "limit": limit}
        if status:
            params["status"] = status
        if platform:
            params["platform"] = platform
        if profile_id:
            params["profileId"] = profile_id
        return self._client._get(self._BASE_PATH, params=params)

    def get(self, post_id: str) -> dict[str, Any]:
        """Get a single post by ID."""
        return self._client._get(f"{self._BASE_PATH}/{post_id}")

    def create(
        self,
        *,
        content: str,
        platforms: list[dict[str, Any]],
        title: str | None = None,
        media_items: list[dict[str, Any]] | None = None,
        scheduled_for: datetime | str | None = None,
        publish_now: bool = False,
        is_draft: bool = False,
        timezone: str = "UTC",
        tags: list[str] | None = None,
        hashtags: list[str] | None = None,
        tiktok_settings: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        """Create a new post."""
        payload: dict[str, Any] = {
            "content": content,
            "platforms": platforms,
            "timezone": timezone,
        }
        if title:
            payload["title"] = title
        if media_items:
            payload["mediaItems"] = media_items
        if scheduled_for:
            payload["scheduledFor"] = (
                scheduled_for.isoformat()
                if isinstance(scheduled_for, datetime)
                else scheduled_for
            )
        if publish_now:
            payload["publishNow"] = True
        if is_draft:
            payload["isDraft"] = True
        if tags:
            payload["tags"] = tags
        if hashtags:
            payload["hashtags"] = hashtags
        if tiktok_settings:
            payload["tiktokSettings"] = tiktok_settings

        return self._client._post(self._BASE_PATH, data=payload)

    def update(self, post_id: str, **kwargs: Any) -> dict[str, Any]:
        """Update an existing post."""
        if "scheduled_for" in kwargs:
            sf = kwargs.pop("scheduled_for")
            kwargs["scheduledFor"] = sf.isoformat() if isinstance(sf, datetime) else sf
        return self._client._put(f"{self._BASE_PATH}/{post_id}", data=kwargs)

    def delete(self, post_id: str) -> dict[str, Any]:
        """Delete a post."""
        return self._client._delete(f"{self._BASE_PATH}/{post_id}")

    def retry(self, post_id: str) -> dict[str, Any]:
        """Retry a failed post."""
        return self._client._post(f"{self._BASE_PATH}/{post_id}/retry")

    def bulk_upload(self, file_path: str | Path) -> dict[str, Any]:
        """Bulk upload posts from a CSV file."""
        path = Path(file_path)
        with open(path, "rb") as f:
            return self._client._post(
                f"{self._BASE_PATH}/bulk-upload",
                files={"file": (path.name, f, "text/csv")},
            )

    # Async methods
    async def alist(
        self,
        *,
        page: int = 1,
        limit: int = 10,
        status: str | None = None,
        platform: str | None = None,
    ) -> dict[str, Any]:
        """List posts asynchronously."""
        params: dict[str, Any] = {"page": page, "limit": limit}
        if status:
            params["status"] = status
        if platform:
            params["platform"] = platform
        return await self._client._aget(self._BASE_PATH, params=params)

    async def aget(self, post_id: str) -> dict[str, Any]:
        """Get a post asynchronously."""
        return await self._client._aget(f"{self._BASE_PATH}/{post_id}")

    async def acreate(self, **kwargs: Any) -> dict[str, Any]:
        """Create a post asynchronously."""
        if "scheduled_for" in kwargs:
            sf = kwargs.pop("scheduled_for")
            kwargs["scheduledFor"] = sf.isoformat() if isinstance(sf, datetime) else sf
        return await self._client._apost(self._BASE_PATH, data=kwargs)

    async def aupdate(self, post_id: str, **kwargs: Any) -> dict[str, Any]:
        """Update a post asynchronously."""
        if "scheduled_for" in kwargs:
            sf = kwargs.pop("scheduled_for")
            kwargs["scheduledFor"] = sf.isoformat() if isinstance(sf, datetime) else sf
        return await self._client._aput(f"{self._BASE_PATH}/{post_id}", data=kwargs)

    async def adelete(self, post_id: str) -> dict[str, Any]:
        """Delete a post asynchronously."""
        return await self._client._adelete(f"{self._BASE_PATH}/{post_id}")
