"""API 路由 — Daemon 控制"""

from __future__ import annotations

from fastapi import APIRouter

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


@router.get("/status")
async def daemon_status():
    from src.main import get_ticker, config
    t = get_ticker()
    return {
        "status": "running",
        "version": "3.0.0",
        "ticker_running": t is not None and t.is_running,
        "tick_count": t.tick_count if t else 0,
        "config": {
            "tick_interval": config.get("daemon", {}).get("tick_interval", 30),
            "max_global_agents": config.get("daemon", {}).get("max_global_agents", 5),
        },
    }


@router.post("/tick")
async def manual_tick():
    """触发手动 tick"""
    from src.main import get_ticker
    t = get_ticker()
    if t is None:
        return {"ok": False, "error": "Ticker not initialized"}
    result = await t.manual_tick()
    return {"ok": True, "result": result}


@router.get("/sessions")
async def daemon_sessions():
    """列出活跃的 Agent sessions"""
    from src.main import get_ticker
    t = get_ticker()
    if t is None:
        return {"sessions": {}}
    dispatcher = t.dispatcher
    if dispatcher is None or dispatcher.spawner is None:
        return {"sessions": {}}
    return {"sessions": dispatcher.spawner.active_sessions}
