"""
Agent 路由
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from datetime import datetime
from app.models import db, Agent

agents_bp = Blueprint('agents', __name__)


@agents_bp.route('/', methods=['GET'])
@jwt_required()
def get_agents():
    """获取 Agent 列表"""
    agents = Agent.query.all()
    return jsonify({'agents': [a.to_dict() for a in agents]}), 200


@agents_bp.route('/<agent_id>', methods=['GET'])
@jwt_required()
def get_agent(agent_id):
    """获取 Agent 详情"""
    agent = Agent.query.get(agent_id)
    if not agent:
        return jsonify({'error': 'Agent not found'}), 404
    return jsonify({'agent': agent.to_dict()}), 200


@agents_bp.route('/<agent_id>/status', methods=['GET'])
@jwt_required()
def get_agent_status(agent_id):
    """获取 Agent 实时状态"""
    agent = Agent.query.get(agent_id)
    if not agent:
        return jsonify({'error': 'Agent not found'}), 404
    
    return jsonify({
        'agent_id': agent.id,
        'status': agent.status,
        'current_sessions': agent.current_sessions,
        'last_heartbeat': agent.last_heartbeat.isoformat() if agent.last_heartbeat else None
    }), 200


@agents_bp.route('/<agent_id>/config', methods=['PUT'])
@jwt_required()
def update_agent_config(agent_id):
    """更新 Agent 配置"""
    agent = Agent.query.get(agent_id)
    if not agent:
        return jsonify({'error': 'Agent not found'}), 404
    
    data = request.get_json()
    
    if 'name' in data:
        agent.name = data['name']
    if 'display_name' in data:
        agent.display_name = data['display_name']
    if 'capabilities' in data:
        agent.capabilities = data['capabilities']
    if 'priority' in data:
        agent.priority = data['priority']
    if 'weight' in data:
        agent.weight = data['weight']
    
    db.session.commit()
    
    return jsonify({'agent': agent.to_dict()}), 200


@agents_bp.route('/<agent_id>/heartbeat', methods=['POST'])
def agent_heartbeat(agent_id):
    """Agent 心跳上报"""
    agent = Agent.query.get(agent_id)
    if not agent:
        return jsonify({'error': 'Agent not found'}), 404
    
    agent.last_heartbeat = datetime.utcnow()
    agent.status = 'online'
    db.session.commit()
    
    return jsonify({'status': 'ok'}), 200


@agents_bp.route('/available', methods=['GET'])
@jwt_required()
def get_available_agents():
    """获取可用 Agent 列表"""
    agents = Agent.query.filter_by(status='online').all()
    return jsonify({'agents': [a.to_dict() for a in agents]}), 200
