# 说话人蓝图
# 处理说话人的增删改查和搜索

from flask import Blueprint, request, jsonify, current_app
from flask_login import login_required, current_user
from datetime import datetime

from src.clients import db
from src.models import Speaker

# 创建说话人蓝图
speaker_bp = Blueprint('speaker', __name__)

# 全局变量
csrf = None

def init_speaker_bp(csrf_instance):
    """初始化蓝图所需的全局变量"""
    global csrf
    csrf = csrf_instance

@speaker_bp.route('/speakers', methods=['GET'])
@login_required
def get_speakers():
    """获取当前用户的所有说话人，按使用频率和最近使用时间排序"""
    try:
        speakers = Speaker.query.filter_by(user_id=current_user.id)\
                               .order_by(Speaker.use_count.desc(), Speaker.last_used.desc())\
                               .all()
        return jsonify([speaker.to_dict() for speaker in speakers])
    except Exception as e:
        current_app.logger.error(f"获取说话人列表时出错: {e}")
        return jsonify({'error': str(e)}), 500

@speaker_bp.route('/speakers/search', methods=['GET'])
@login_required
def search_speakers():
    """按名称搜索说话人，用于自动补全功能"""
    try:
        query = request.args.get('q', '').strip()
        if not query:
            return jsonify([])
        
        speakers = Speaker.query.filter_by(user_id=current_user.id)\
                               .filter(Speaker.name.ilike(f'%{query}%'))\
                               .order_by(Speaker.use_count.desc(), Speaker.last_used.desc())\
                               .limit(10)\
                               .all()
        
        return jsonify([speaker.to_dict() for speaker in speakers])
    except Exception as e:
        current_app.logger.error(f"搜索说话人时出错: {e}")
        return jsonify({'error': str(e)}), 500

@speaker_bp.route('/speakers', methods=['POST'])
@login_required
def create_speaker():
    """创建新说话人或更新现有说话人"""
    try:
        data = request.json
        name = data.get('name', '').strip()
        
        if not name:
            return jsonify({'error': '说话人名称为必填项'}), 400
        
        # 检查当前用户是否已存在同名说话人
        existing_speaker = Speaker.query.filter_by(user_id=current_user.id, name=name).first()
        
        if existing_speaker:
            # 更新使用统计
            existing_speaker.use_count += 1
            existing_speaker.last_used = datetime.utcnow()
            db.session.commit()
            return jsonify(existing_speaker.to_dict())
        else:
            # 创建新说话人
            speaker = Speaker(
                name=name,
                user_id=current_user.id,
                use_count=1,
                created_at=datetime.utcnow(),
                last_used=datetime.utcnow()
            )
            db.session.add(speaker)
            db.session.commit()
            return jsonify(speaker.to_dict()), 201
            
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"创建说话人时出错: {e}")
        return jsonify({'error': str(e)}), 500

@speaker_bp.route('/speakers/<int:speaker_id>', methods=['DELETE'])
@login_required
def delete_speaker(speaker_id):
    """删除说话人"""
    try:
        speaker = Speaker.query.filter_by(id=speaker_id, user_id=current_user.id).first()
        if not speaker:
            return jsonify({'error': '说话人不存在'}), 404
        
        db.session.delete(speaker)
        db.session.commit()
        return jsonify({'success': True})
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"删除说话人时出错: {e}")
        return jsonify({'error': str(e)}), 500

@speaker_bp.route('/speakers/delete_all', methods=['DELETE'])
@login_required
def delete_all_speakers():
    """删除当前用户的所有说话人"""
    try:
        deleted_count = Speaker.query.filter_by(user_id=current_user.id).delete()
        db.session.commit()
        return jsonify({'success': True, 'deleted_count': deleted_count})
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"删除所有说话人时出错: {e}")
        return jsonify({'error': str(e)}), 500
