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

from src.clients import db
from src.models import HotWord, YlHotWord


hotword_bp = Blueprint('hotword', __name__)

csrf = None


SCENE_YL = 'yl'
SCENE_CG = 'cg'


def init_hotword_bp(csrf_instance):
    """Initialize blueprint dependencies."""
    global csrf
    csrf = csrf_instance


def _normalize_scene(scene):
    return SCENE_YL if str(scene or '').strip().lower() == SCENE_YL else SCENE_CG


def _hotword_model_for_scene(scene):
    return YlHotWord if _normalize_scene(scene) == SCENE_YL else HotWord


def _parse_hotwords_text(hotwords_text):
    """Parse textarea content into hotword rows."""
    new_hotwords = []

    for raw_line in (hotwords_text or '').strip().split('\n'):
        line = raw_line.strip()
        if not line:
            continue

        parts = line.split()
        if len(parts) >= 2:
            keyword = parts[0].strip()
            try:
                weight = int(parts[1])
            except (TypeError, ValueError):
                weight = 1
        else:
            keyword = line
            weight = 1

        if keyword:
            new_hotwords.append({'keyword': keyword, 'weight': weight})

    return new_hotwords


def _format_hotwords_text(hotwords):
    return '\n'.join([f'{hw.keyword} {hw.weight}' for hw in hotwords])


@hotword_bp.route('/api/hotwords', methods=['GET'])
@login_required
def get_hotwords():
    """Get scene hotwords."""
    try:
        scene = _normalize_scene(request.args.get('scene'))
        hotword_model = _hotword_model_for_scene(scene)
        hotwords = hotword_model.query.order_by(hotword_model.weight.desc(), hotword_model.keyword).all()
        hotwords_text = _format_hotwords_text(hotwords)
        return jsonify({
            'success': True,
            'scene': scene,
            'hotwords': [hw.to_dict() for hw in hotwords],
            'text_format': hotwords_text,
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@hotword_bp.route('/api/hotwords', methods=['POST'])
@login_required
def update_hotwords():
    """Replace existing hotwords for the selected scene."""
    try:
        if not current_user.is_admin:
            return jsonify({'error': '只有管理员可以修改热词配置'}), 403

        data = request.json
        if not data:
            return jsonify({'error': '没有提供数据'}), 400

        scene = _normalize_scene(data.get('scene') or request.args.get('scene'))
        hotword_model = _hotword_model_for_scene(scene)
        hotwords_text = data.get('hotwords', '')
        if not hotwords_text.strip():
            return jsonify({'error': '热词内容不能为空'}), 400

        new_hotwords = _parse_hotwords_text(hotwords_text)
        if not new_hotwords:
            return jsonify({'error': '没有有效的热词数据'}), 400

        try:
            hotword_model.query.delete()

            for hw_data in new_hotwords:
                hotword = hotword_model(
                    keyword=hw_data['keyword'],
                    weight=hw_data['weight']
                )
                db.session.add(hotword)

            db.session.commit()

            return jsonify({
                'success': True,
                'scene': scene,
                'message': f'成功更新 {len(new_hotwords)} 个热词',
                'hotwords': [hw.to_dict() for hw in hotword_model.query.all()],
                'text_format': hotwords_text
            })
        except Exception as e:
            db.session.rollback()
            return jsonify({'error': f'更新热词时发生错误: {str(e)}'}), 500
    except Exception as e:
        return jsonify({'error': str(e)}), 500
