from fastapi import APIRouter, HTTPException
from app.core.scheduler import scheduler

router = APIRouter(prefix="/api/v1/bot", tags=["bot"])

# In-memory bot state — persists within a single process
_bot_state = {"running": False, "mode": "SIMULATION"}


@router.post("/start")
async def start_bot():
    """Start the bot (enables scheduled jobs)."""
    if _bot_state["running"]:
        raise HTTPException(status_code=400, detail="Bot is already running")
    if not scheduler.running:
        raise HTTPException(status_code=500, detail="Scheduler not initialised")
    # Resume all paused jobs
    for job in scheduler.get_jobs():
        job.resume()
    _bot_state["running"] = True
    return {"status": "started", "message": "Bot is now running"}


@router.post("/stop")
async def stop_bot():
    """Pause the bot (suspend scheduled jobs without shutting down)."""
    if not _bot_state["running"]:
        raise HTTPException(status_code=400, detail="Bot is already stopped")
    for job in scheduler.get_jobs():
        job.pause()
    _bot_state["running"] = False
    return {"status": "stopped", "message": "Bot has been paused"}


@router.get("/status")
async def bot_status():
    """Return current bot state and scheduler info."""
    jobs = []
    if scheduler.running:
        for job in scheduler.get_jobs():
            jobs.append({
                "id": job.id,
                "next_run": job.next_run_time.isoformat() if job.next_run_time else None,
            })
    return {
        "running": _bot_state["running"],
        "mode": _bot_state["mode"],
        "scheduler_running": scheduler.running,
        "jobs": jobs,
    }
