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 ZhihuPublisher(ContentPublisher):
    platform: str = "zhihu"

    API_BASE = "https://api.zhihu.com"

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

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

        headers = {
            "Authorization": f"Bearer {settings.ZHIHU_ACCESS_TOKEN}",
            "Content-Type": "application/json",
        }
        payload = {
            "title": title,
            "content": content,
            "comment_permission": kwargs.get("comment_permission", 1),
        }
        if kwargs.get("column_id"):
            payload["column_id"] = kwargs["column_id"]

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

                if resp.status_code in (200, 201):
                    return PublishResult(
                        success=True,
                        platform=self.platform,
                        article_id=str(data.get("id", "")),
                        article_url=data.get("url", ""),
                        raw_response=data,
                    )
                else:
                    return PublishResult(
                        success=False,
                        platform=self.platform,
                        error=data.get("error", {}).get("message", str(data)),
                        raw_response=data,
                    )
        except Exception as e:
            logger.error(f"Zhihu 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}/me",
                    headers={"Authorization": f"Bearer {settings.ZHIHU_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="zhihu")
            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}/articles/{article_id}",
                    headers={"Authorization": f"Bearer {settings.ZHIHU_ACCESS_TOKEN}"},
                )
                return resp.json()
        except Exception as e:
            return {"article_id": article_id, "error": str(e)}
