"""
发布管理 API
"""
from fastapi import APIRouter, HTTPException, BackgroundTasks
from pydantic import BaseModel
from typing import List, Optional
from datetime import datetime
from loguru import logger
from app.services.publish_service import PublishService

router = APIRouter()
publish_service = PublishService()

class PublishRequest(BaseModel):
    """Video publish request model"""
    video_path: str
    platform: str
    title: str
    tags: List[str] = []
    description: str = ""
    publish_time: Optional[datetime] = None

class PublishResponse(BaseModel):
    """Video publish response model"""
    success: bool
    message: str
    platform: str
    url: Optional[str] = None

# Supported platforms for validation
SUPPORTED_PLATFORMS = {"bilibili", "douyin", "xiaohongshu"}

@router.post("/", response_model=PublishResponse)
async def publish_video(request: PublishRequest, background_tasks: BackgroundTasks):
    """发布视频到指定平台"""
    # Validate platform
    if request.platform not in SUPPORTED_PLATFORMS:
        raise HTTPException(
            status_code=400, 
            detail=f"不支持的平台: {request.platform}。支持的平台: {', '.join(SUPPORTED_PLATFORMS)}"
        )
    
    try:
        result = await publish_service.publish(
            video_path=request.video_path,
            platform=request.platform,
            title=request.title,
            tags=request.tags,
            description=request.description,
            publish_time=request.publish_time
        )
        return PublishResponse(
            success=result.get("success", False),
            message=result.get("message", ""),
            platform=request.platform,
            url=result.get("url")
        )
    except Exception as e:
        logger.error(f"发布失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/platforms")
async def list_platforms():
    return {"platforms": [{"id": pid, **pinfo} for pid, pinfo in publish_service.PLATFORMS.items()]}

@router.get("/accounts")
async def list_accounts():
    return {"accounts": publish_service.get_accounts()}

@router.post("/login/{platform}")
async def login_platform(platform: str):
    """触发平台QR码登录"""
    if platform not in SUPPORTED_PLATFORMS:
        raise HTTPException(status_code=400, detail=f"不支持的平台: {platform}")
    
    result = await publish_service.login(platform)
    if result.get("success"):
        return result
    else:
        raise HTTPException(status_code=400, detail=result.get("message"))

@router.post("/logout/{platform}")
async def logout_platform(platform: str):
    """注销平台登录"""
    if platform not in SUPPORTED_PLATFORMS:
        raise HTTPException(status_code=400, detail=f"不支持的平台: {platform}")
    
    result = publish_service.logout(platform)
    return result

@router.get("/login/status/{platform}")
async def get_login_status(platform: str):
    """检查登录状态 (优先检查活跃的扫码会话)"""
    if platform not in SUPPORTED_PLATFORMS:
        raise HTTPException(status_code=400, detail=f"不支持的平台: {platform}")
    
    return publish_service.get_login_session_status(platform)

@router.post("/cookies/save/{platform}")
async def save_platform_cookie(platform: str, cookie_data: dict):
    """
    保存从客户端浏览器提取的Cookie
    
    Args:
        platform: 平台ID
        cookie_data: {"cookie_string": "document.cookie的内容"}
    """
    if platform not in SUPPORTED_PLATFORMS:
        raise HTTPException(status_code=400, detail=f"不支持的平台: {platform}")
    
    cookie_string = cookie_data.get("cookie_string", "")
    if not cookie_string:
        raise HTTPException(status_code=400, detail="cookie_string 不能为空")
    
    result = await publish_service.save_cookie_string(platform, cookie_string)
    
    if result.get("success"):
        return result
    else:
        raise HTTPException(status_code=400, detail=result.get("message"))
