"""
统计路由
"""
from flask import Blueprint, jsonify
from flask_jwt_extended import jwt_required
from app.models import db, User, Session, Agent, Gateway, Message
from sqlalchemy import func

stats_bp = Blueprint('stats', __name__)


@stats_bp.route('/', methods=['GET'])
@jwt_required()
def get_stats():
    """获取系统统计信息"""
    stats = {
        'users': User.query.count(),
        'sessions': Session.query.filter_by(status='active').count(),
        'agents': Agent.query.filter_by(status='online').count(),
        'gateways': Gateway.query.filter_by(status='online').count(),
        'messages': Message.query.count(),
    }
    
    return jsonify({'stats': stats}), 200


@stats_bp.route('/sessions', methods=['GET'])
@jwt_required()
def get_session_stats():
    """获取会话统计"""
    stats = {
        'total': Session.query.count(),
        'active': Session.query.filter_by(status='active').count(),
        'closed': Session.query.filter_by(status='closed').count(),
        'paused': Session.query.filter_by(status='paused').count(),
    }
    
    return jsonify({'stats': stats}), 200


@stats_bp.route('/messages', methods=['GET'])
@jwt_required()
def get_message_stats():
    """获取消息统计"""
    stats = {
        'total': Message.query.count(),
        'sent': Message.query.filter_by(status='sent').count(),
        'delivered': Message.query.filter_by(status='delivered').count(),
        'read': Message.query.filter_by(status='read').count(),
        'failed': Message.query.filter_by(status='failed').count(),
    }
    
    return jsonify({'stats': stats}), 200


@stats_bp.route('/agents', methods=['GET'])
@jwt_required()
def get_agent_stats():
    """获取 Agent 统计"""
    stats = {
        'total': Agent.query.count(),
        'online': Agent.query.filter_by(status='online').count(),
        'offline': Agent.query.filter_by(status='offline').count(),
        'busy': Agent.query.filter_by(status='busy').count(),
    }
    
    return jsonify({'stats': stats}), 200
