import logging
from typing import Optional

import httpx

from app.config import settings
from app.services.distribution.publishers.base import ContentPublisher, PublishResult
from app.services.distribution.publishers.mock_publisher import MockPublisher

logger = logging.getLogger(__name__)


class ToutiaoPublisher(ContentPublisher):
    platform: str = "toutiao"

    API_BASE = "https://open.toutiao.com/api/v2"

    def is_configured(self) -> bool:
        return bool(settings.TOUTIAO_ACCESS_TOKEN)

    async def publish(self, title: str, content: str, **kwargs) -> PublishResult:
        if not self.is_configured():
            mock = MockPublisher(platform="toutiao")
            return await mock.publish(title, content, **kwargs)

        headers = {
            "Authorization": f"Bearer {settings.TOUTIAO_ACCESS_TOKEN}",
            "Content-Type": "application/json",
        }
        payload = {
            "title": title,
            "content": content,
            "source": kwargs.get("source", "原创"),
        }

        try:
            async with httpx.AsyncClient(timeout=30) as client:
                resp = await client.post(
                    f"{self.API_BASE}/article/create",
                    headers=headers,
                    json=payload,
                )
                data = resp.json()

                if resp.status_code in (200, 201) and data.get("code") == 0:
                    item = data.get("data", {})
                    return PublishResult(
                        success=True,
                        platform=self.platform,
                        article_id=str(item.get("article_id", "")),
                        article_url=item.get("article_url", ""),
                        raw_response=data,
                    )
                else:
                    return PublishResult(
                        success=False,
                        platform=self.platform,
                        error=data.get("message", str(data)),
                        raw_response=data,
                    )
        except Exception as e:
            logger.error(f"Toutiao publish error: {e}")
            return PublishResult(
                success=False,
                platform=self.platform,
                error=str(e),
            )

    async def verify_credentials(self) -> bool:
        if not self.is_configured():
            return False
        try:
            async with httpx.AsyncClient(timeout=10) as client:
                resp = await client.get(
                    f"{self.API_BASE}/user/info",
                    headers={"Authorization": f"Bearer {settings.TOUTIAO_ACCESS_TOKEN}"},
                )
                return resp.status_code == 200
        except Exception:
            return False

    async def get_article_status(self, article_id: str) -> dict:
        if not self.is_configured():
            mock = MockPublisher(platform="toutiao")
            return await mock.get_article_status(article_id)
        try:
            async with httpx.AsyncClient(timeout=10) as client:
                resp = await client.get(
                    f"{self.API_BASE}/article/info",
                    params={"article_id": article_id},
                    headers={"Authorization": f"Bearer {settings.TOUTIAO_ACCESS_TOKEN}"},
                )
                return resp.json()
        except Exception as e:
            return {"article_id": article_id, "error": str(e)}
