# 宇之然内容创作平台 - 文章发布API

from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
import random

from ..core.security import get_current_user, create_audit_log
from ..database import get_db
from ..models import Topic, User

router = APIRouter()

class PublishRequest(BaseModel):
    topic_id: int

@router.post("/create")
async def create_publication(
    request: PublishRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """发布选题到各平台"""
    
    # 检查选题是否存在
    topic = db.query(Topic).filter(Topic.id == request.topic_id).first()
    if not topic:
        raise HTTPException(status_code=404, detail="选题不存在")
    
    # 检查选题状态是否正确（必须是待发布）
    if topic.status != "待发布":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"选题状态不正确，当前状态: {topic.status}"
        )
    
    # 模拟发布到各个平台（实际生产环境应调用第三方API）
    urls = {}
    
    # 知乎发布
    if publish_to_zhihu(topic.title):
        urls["zhihu"] = f"https://zhihu.com/article/{random.randint(100000, 999999)}"
    
    # 微信公众号发布
    if publish_to_wechat(topic.title):
        urls["wechat"] = f"https://mp.weixin.qq.com/s/{random.randint(100000, 999999)}"
    
    # 小红书发布
    if publish_to_xiaohongshu(topic.title):
        urls["xiaohongshu"] = f"https://www.xiaohongshu.com/discovery/item/{random.randint(100000, 999999)}"
    
    # 更新选题状态和发布时间
    topic.published_at = datetime.utcnow()
    topic.published_urls = urls
    topic.status = "已发布"
    topic.updated_at = datetime.utcnow()
    
    db.commit()
    
    # 记录审计日志
    create_audit_log(
        db=db,
        user_id=current_user.id,
        action="publish",
        resource_type="topic",
        resource_id=topic.id,
        details=f"发布到平台: {list(urls.keys())}"
    )
    
    return {
        "success": True,
        "urls": urls,
        "published_at": topic.published_at.isoformat() if topic.published_at else None
    }

def publish_to_zhihu(title: str) -> bool:
    """模拟发布到知乎"""
    # 实际实现应调用知乎API
    import random
    return random.choice([True, False])

def publish_to_wechat(title: str) -> bool:
    """模拟发布到微信公众号"""
    # 实际实现应调用微信公众号API
    import random
    return random.choice([True, False])

def publish_to_xiaohongshu(title: str) -> bool:
    """模拟发布到小红书"""
    # 实际实现应调用小红书API
    import random
    return random.choice([True, False])