"""冷热调度 — 空闲超时停止、LRU 置换（基于 ToolStatusManager）"""

from __future__ import annotations

import logging
from datetime import datetime, timezone

from tool_agent.config import settings
from tool_agent.router.status import ToolStatusManager, ProcessState

logger = logging.getLogger(__name__)


class Scheduler:
    """管理工具进程生命周期：空闲休眠、LRU 置换"""

    def __init__(self, status_manager: ToolStatusManager) -> None:
        self._status_manager = status_manager

    async def check_idle(self) -> list[str]:
        """检查空闲超时的工具，停止并返回 tool_id 列表"""
        now = datetime.now(timezone.utc)
        stopped = []
        for route in self._status_manager.list_status():
            if route.state != ProcessState.RUNNING or not route.started_at:
                continue
            elapsed = (now - route.started_at).total_seconds()
            if elapsed > settings.cold_tool_idle_timeout_s:
                self._status_manager.stop_tool(route.tool_id)
                stopped.append(route.tool_id)
                logger.info(f"Idle timeout: stopped '{route.tool_id}'")
        return stopped

    async def evict_lru(self) -> str | None:
        """LRU 置换：运行中工具数超限时，停止最久启动的"""
        running = [
            r for r in self._status_manager.list_status()
            if r.state == ProcessState.RUNNING and r.started_at
        ]
        if len(running) <= settings.hot_tool_max_containers:
            return None
        oldest = min(running, key=lambda r: r.started_at)
        self._status_manager.stop_tool(oldest.tool_id)
        logger.info(f"LRU evicted: '{oldest.tool_id}'")
        return oldest.tool_id
