"""
工作手机SDK v3.0 - 设备发现路由
提供局域网自动发现、服务器信息、扫描等 API
"""

from fastapi import APIRouter
from services.discovery_service import discovery_service

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


@router.get("/server-info")
async def get_server_info():
    """返回本服务器信息（IP、端口、WS 地址等）"""
    return {"code": 200, "data": discovery_service.get_server_info()}


@router.post("/scan-lan")
async def scan_lan(timeout: float = 3.0):
    """扫描局域网中的 SDK 服务器"""
    if timeout > 10:
        timeout = 10
    results = await discovery_service.scan_lan(timeout=timeout)
    return {
        "code": 200,
        "data": {
            "servers": results,
            "count": len(results),
        }
    }


@router.get("/last-scan")
async def get_last_scan():
    """获取上次扫描结果"""
    return {"code": 200, "data": discovery_service.get_last_scan()}


@router.post("/listen-beacon")
async def listen_beacon(timeout: float = 5.0):
    """监听 UDP beacon 发现服务器"""
    if timeout > 15:
        timeout = 15
    servers = await discovery_service.listen_beacon(timeout=timeout)
    return {
        "code": 200,
        "data": {
            "servers": servers,
            "count": len(servers),
        }
    }


@router.post("/beacon/start")
async def start_beacon():
    """启动 UDP beacon 广播"""
    await discovery_service.start_beacon(port=discovery_service.server_port)
    return {"code": 200, "data": {"status": "beacon_started"}}


@router.post("/beacon/stop")
async def stop_beacon():
    """停止 UDP beacon 广播"""
    await discovery_service.stop_beacon()
    return {"code": 200, "data": {"status": "beacon_stopped"}}
