"""
Content Queue & Calendar REST API
GET    /api/queue                          — xem queue hiện tại
POST   /api/queue/{content_id}             — thêm vào queue
DELETE /api/queue/{content_id}             — xóa khỏi queue
POST   /api/queue/reorder                  — drag-drop reorder
GET    /api/queue/calendar                 — calendar view (theo tuần)
GET    /api/queue/slots                    — xem posting slots
PUT    /api/queue/slots                    — update slots
POST   /api/queue/slots/reset              — reset về default
GET    /api/queue/retry-state              — trạng thái retry publisher
POST   /api/queue/publish-tick             — manual trigger publish engine tick
"""

import logging
from typing import Optional

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from common.social.post_queue import (
    add_to_queue, get_calendar_week, get_queue,
    get_slots, remove_from_queue, reorder_queue,
    reset_slots_to_default, save_slots,
)
from common.social.scheduler import get_retry_state, _engine

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/queue", tags=["Content Queue"])


class ReorderBody(BaseModel):
    ordered_content_ids: list[str]


class AddToQueueBody(BaseModel):
    priority: bool = False


@router.get("")
async def get_current_queue():
    """Lấy queue hiện tại kèm content data."""
    queue = get_queue()
    return {"queue": queue, "total": len(queue)}


@router.post("/{content_id}")
async def add_content_to_queue(content_id: str, body: AddToQueueBody = AddToQueueBody()):
    """Thêm content vào queue."""
    queue = add_to_queue(content_id, priority=body.priority)
    return {"ok": True, "queue": queue}


@router.delete("/{content_id}")
async def remove_content_from_queue(content_id: str):
    """Xóa content khỏi queue."""
    queue = remove_from_queue(content_id)
    return {"ok": True, "queue": queue}


@router.post("/reorder")
async def reorder(body: ReorderBody):
    """Drag-drop reorder — pass danh sách content_id theo thứ tự mới."""
    queue = reorder_queue(body.ordered_content_ids)
    return {"ok": True, "queue": queue}


@router.get("/calendar")
async def calendar_week(week_offset: int = 0):
    """Calendar view theo tuần. week_offset=0 → tuần này."""
    return get_calendar_week(week_offset=week_offset)


@router.get("/slots")
async def get_posting_slots():
    """Lấy posting slots hiện tại."""
    return {"slots": get_slots()}


@router.put("/slots")
async def update_slots(slots: list[dict]):
    """Cập nhật posting slots. Input: [{day, hour, minute, label}]"""
    saved = save_slots(slots)
    return {"ok": True, "slots": saved}


@router.post("/slots/reset")
async def reset_slots():
    """Reset posting slots về default của BrightBean."""
    slots = reset_slots_to_default()
    return {"ok": True, "slots": slots}


@router.get("/retry-state")
async def retry_state():
    """Xem trạng thái retry của publisher engine."""
    return {"retry_state": get_retry_state()}


@router.post("/publish-tick")
async def manual_publish_tick():
    """Manual trigger một publish engine tick (dùng khi debug/testing)."""
    import asyncio
    loop = asyncio.get_event_loop()
    count = await loop.run_in_executor(None, _engine.poll_and_publish)
    return {"ok": True, "published_count": count}
