"""Core bot action routes: conversation reset, sleep, wake, bedtime."""

from fastapi import APIRouter
from fastapi.responses import JSONResponse
import globals
from commands.actions import (
    force_sleep,
    wake_up,
    reset_conversation,
)
from routes.models import ConversationResetRequest
from utils.logger import get_logger

logger = get_logger('api')

router = APIRouter()


@router.post("/conversation/reset")
def reset_convo(data: ConversationResetRequest):
    reset_conversation(data.user_id)
    return {"status": "ok", "message": "Conversation reset"}


@router.post("/sleep")
async def force_sleep_endpoint():
    await force_sleep()
    return {"status": "ok", "message": "Miku is now sleeping"}


@router.post("/wake")
async def wake_up_endpoint():
    await wake_up()
    return {"status": "ok", "message": "Miku is now awake"}


@router.post("/bedtime")
async def bedtime_endpoint(guild_id: int = None):
    # If guild_id is provided, send bedtime reminder only to that server
    # If no guild_id, send to all servers (legacy behavior)
    if globals.client and globals.client.loop and globals.client.loop.is_running():
        if guild_id is not None:
            # Send to specific server only
            from utils.scheduled import send_bedtime_reminder_for_server
            globals.client.loop.create_task(send_bedtime_reminder_for_server(guild_id, globals.client))
            return {"status": "ok", "message": f"Bedtime reminder queued for server {guild_id}"}
        else:
            # Send to all servers (legacy behavior)
            from utils.scheduled import send_bedtime_now
            globals.client.loop.create_task(send_bedtime_now())
            return {"status": "ok", "message": "Bedtime reminder queued for all servers"}
    else:
        return JSONResponse(status_code=503, content={"status": "error", "message": "Bot not ready"})
