"""
Content Approval REST API Route
POST   /api/content                    — tạo content mới (AI agent)
GET    /api/content                    — list content (filter by status)
GET    /api/content/{id}               — chi tiết content
POST   /api/content/{id}/submit        — submit for review
POST   /api/content/{id}/approve       — marketing approve
POST   /api/content/{id}/reject        — marketing reject
POST   /api/content/{id}/changes       — request changes
POST   /api/content/{id}/schedule      — assign vào queue
POST   /api/content/{id}/publish-now   — publish ngay lập tức
GET    /api/content/stats              — approval stats
"""

import logging
from typing import Optional

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from common.social.approval_gate import (approve_content, create_content, get_approval_stats, get_content,
                                         list_contents, reject_content, request_changes, schedule_content)
from common.social.post_queue import add_to_queue
from common.social.scheduler import manual_publish

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/content", tags=["Content Approval"])


# ─── Request models ───────────────────────────────────────────────────────────

class CreateContentBody(BaseModel):
    title: str
    caption: str
    platforms: list[str]
    image_urls: list[str] = []
    tags: list[str] = []
    created_by: str = "ai_agent"
    metadata: dict = {}
    auto_submit: bool = False  # Nếu True: tạo xong → submit ngay


class ReviewBody(BaseModel):
    actor: str = "marketing_team"
    comment: str = ""


class ScheduleBody(BaseModel):
    scheduled_at: str
    priority: bool = False


# ─── Endpoints ───────────────────────────────────────────────────────────────

@router.post("")
async def create_new_content(body: CreateContentBody):
    """Tạo content mới. Thường được AI stylist engine gọi."""
    content = create_content(
        title=body.title,
        caption=body.caption,
        platforms=body.platforms,
        image_urls=body.image_urls,
        created_by=body.created_by,
        tags=body.tags,
        metadata=body.metadata,
    )
    if body.auto_submit:
        from common.social.approval_gate import submit_for_review
        content = submit_for_review(content["id"], submitted_by=body.created_by)

    return {"ok": True, "content": content}


@router.get("")
async def list_all_contents(
    status: Optional[str] = None,
    platform: Optional[str] = None,
    limit: int = 50,
    offset: int = 0,
):
    """List tất cả content với filter."""
    return list_contents(status=status, platform=platform, limit=limit, offset=offset)


@router.get("/stats")
async def approval_stats():
    """Thống kê trạng thái content."""
    return get_approval_stats()


@router.get("/{content_id}")
async def get_content_detail(content_id: str):
    content = get_content(content_id)
    if not content:
        raise HTTPException(status_code=404, detail="Content not found")
    return content


@router.post("/{content_id}/pretest")
async def pretest_content(content_id: str):
    """Chạy reaction simulation cho content để marketing xem trước."""
    from common.social.approval_gate import get_content, update_content_metadata
    from agent.reaction_agent import run_reaction_simulation
    from api.reaction_simulator.reaction_db import save_reaction_run
    
    content = get_content(content_id)
    if not content:
        raise HTTPException(status_code=404, detail="Content not found")
        
    caption = content.get("caption", "")
    if not caption:
        raise HTTPException(status_code=400, detail="Content has no caption")
        
    try:
        result = await run_reaction_simulation(
            campaign_type="product_launch",
            campaign_content=caption,
            persona_weights=None,
            model_name=None,
        )
        result["campaign_content"] = caption
        run_id = save_reaction_run(result, is_mock=False)
        update_content_metadata(content_id, {"pretest_run_id": run_id})
        result["run_id"] = run_id
        return {"ok": True, "result": result}
    except Exception as e:
        logger.error(f"Pretest failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/{content_id}/submit")
async def submit_content(content_id: str, body: ReviewBody):
    from common.social.approval_gate import submit_for_review
    try:
        content = submit_for_review(content_id, submitted_by=body.actor)
        return {"ok": True, "content": content}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/{content_id}/approve")
async def approve(content_id: str, body: ReviewBody):
    try:
        content = approve_content(content_id, approved_by=body.actor, comment=body.comment)
        # Tự động thêm vào queue
        add_to_queue(content_id)
        return {"ok": True, "content": content, "queued": True}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/{content_id}/reject")
async def reject(content_id: str, body: ReviewBody):
    if not body.comment:
        raise HTTPException(status_code=422, detail="Phải có lý do khi từ chối.")
    try:
        content = reject_content(content_id, rejected_by=body.actor, comment=body.comment)
        return {"ok": True, "content": content}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/{content_id}/changes")
async def request_change(content_id: str, body: ReviewBody):
    if not body.comment:
        raise HTTPException(status_code=422, detail="Phải mô tả cần sửa gì.")
    try:
        content = request_changes(content_id, requested_by=body.actor, comment=body.comment)
        return {"ok": True, "content": content}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/{content_id}/schedule")
async def schedule(content_id: str, body: ScheduleBody):
    try:
        content = schedule_content(content_id, scheduled_at=body.scheduled_at)
        add_to_queue(content_id, priority=body.priority)
        return {"ok": True, "content": content}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/{content_id}/publish-now")
async def publish_now(content_id: str):
    """Publish ngay lập tức — bypass queue timing."""
    result = manual_publish(content_id)
    if not result.get("success"):
        raise HTTPException(status_code=500, detail=result.get("error", "Publish failed"))
    return {"ok": True, "result": result}
