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

sessions_bp = Blueprint('sessions', __name__)


@sessions_bp.route('/', methods=['GET'])
@jwt_required()
def get_sessions():
    """获取会话列表"""
    user_id = get_jwt_identity()
    sessions = Session.query.filter_by(user_id=user_id).all()
    
    return jsonify({
        'sessions': [s.to_dict() for s in sessions]
    }), 200


@sessions_bp.route('/', methods=['POST'])
@jwt_required()
def create_session():
    """创建会话"""
    user_id = get_jwt_identity()
    data = request.get_json()
    
    title = data.get('title', 'New Session')
    agent_id = data.get('agent_id')
    priority = data.get('priority', 5)
    
    # 如果没有指定 Agent，分配一个
    if not agent_id:
        agent = Agent.query.filter_by(status='online').order_by(
            Agent.current_sessions.asc()
        ).first()
        if agent:
            agent_id = agent.id
    
    session = Session(
        user_id=user_id,
        primary_agent_id=agent_id,
        title=title,
        status='active'
    )
    
    db.session.add(session)
    db.session.commit()
    
    return jsonify({
        'session': session.to_dict()
    }), 201


@sessions_bp.route('/<session_id>', methods=['GET'])
@jwt_required()
def get_session(session_id):
    """获取会话详情"""
    user_id = get_jwt_identity()
    session = Session.query.filter_by(id=session_id, user_id=user_id).first()
    
    if not session:
        return jsonify({'error': 'Session not found'}), 404
    
    return jsonify({'session': session.to_dict()}), 200


@sessions_bp.route('/<session_id>/close', methods=['PUT'])
@jwt_required()
def close_session(session_id):
    """关闭会话"""
    user_id = get_jwt_identity()
    session = Session.query.filter_by(id=session_id, user_id=user_id).first()
    
    if not session:
        return jsonify({'error': 'Session not found'}), 404
    
    session.status = 'closed'
    session.updated_at = datetime.utcnow()
    db.session.commit()
    
    return jsonify({'message': 'Session closed', 'session': session.to_dict()}), 200


@sessions_bp.route('/<session_id>/messages', methods=['GET'])
@jwt_required()
def get_session_messages(session_id):
    """获取会话消息"""
    user_id = get_jwt_identity()
    session = Session.query.filter_by(id=session_id, user_id=user_id).first()
    
    if not session:
        return jsonify({'error': 'Session not found'}), 404
    
    messages = session.messages.order_by('created_at').all()
    
    return jsonify({
        'messages': [m.to_dict() for m in messages]
    }), 200
