"""
工作手机SDK v3.0 - 抓包服务
与设备端 Frida 配合：启停抓包、拉取数据
"""

import logging
from typing import Dict, List, Any, Optional
from datetime import datetime

logger = logging.getLogger(__name__)

_capture_status: Dict[str, bool] = {}
_capture_data: Dict[str, List[Dict[str, Any]]] = {}
_max_records_per_device = 500


def start_capture(device_id: str) -> Dict[str, Any]:
    if _capture_status.get(device_id):
        return {"success": True, "message": "已在抓包中", "device_id": device_id}
    _capture_status[device_id] = True
    _capture_data[device_id] = []
    logger.info(f"抓包已启动: {device_id}")
    return {"success": True, "message": "抓包已启动", "device_id": device_id}


def stop_capture(device_id: str) -> Dict[str, Any]:
    if not _capture_status.get(device_id):
        return {"success": True, "message": "未在抓包", "device_id": device_id}
    _capture_status[device_id] = False
    logger.info(f"抓包已停止: {device_id}")
    return {"success": True, "message": "抓包已停止", "device_id": device_id}


def get_capture_status(device_id: str) -> Dict[str, Any]:
    return {
        "device_id": device_id,
        "running": _capture_status.get(device_id, False),
        "record_count": len(_capture_data.get(device_id, [])),
    }


def get_capture_data(device_id: str, limit: int = 100, since_ts: Optional[float] = None) -> Dict[str, Any]:
    records = _capture_data.get(device_id, [])
    if since_ts is not None:
        records = [r for r in records if r.get("ts", 0) >= since_ts]
    records = records[-limit:] if limit else records
    return {
        "success": True,
        "device_id": device_id,
        "count": len(records),
        "data": records,
    }


def append_capture_record(device_id: str, record: Dict[str, Any]) -> None:
    if device_id not in _capture_data:
        _capture_data[device_id] = []
    rec = {"ts": datetime.now().timestamp(), **record}
    _capture_data[device_id].append(rec)
    if len(_capture_data[device_id]) > _max_records_per_device:
        _capture_data[device_id] = _capture_data[device_id][-_max_records_per_device:]
