from flask import Blueprint, jsonify, request

from services.shap_service import shap_service

shap_bp = Blueprint('shap', __name__, url_prefix='/api/shap')


@shap_bp.route('/global', methods=['GET'])
def get_global_importance():
    try:
        model_type = request.args.get('model', 'random_forest')
        result = shap_service.get_global_importance(model_type)
        return jsonify({'code': 200, 'message': 'success', 'data': result})
    except Exception as e:
        return jsonify({'code': 500, 'message': str(e), 'data': None}), 500


@shap_bp.route('/local', methods=['POST'])
def get_local_explanation():
    try:
        data = request.get_json()
        if not data:
            return jsonify({'code': 400, 'message': 'Request body is required', 'data': None}), 400
        model_type = data.get('model_type', 'random_forest')
        result = shap_service.get_local_explanation(data, model_type)
        return jsonify({'code': 200, 'message': 'success', 'data': result})
    except Exception as e:
        return jsonify({'code': 500, 'message': str(e), 'data': None}), 500


@shap_bp.route('/interaction', methods=['GET'])
def get_interactions():
    try:
        model_type = request.args.get('model', 'random_forest')
        top_n = int(request.args.get('top_n', 10))
        result = shap_service.get_interactions(model_type, top_n)
        return jsonify({'code': 200, 'message': 'success', 'data': result})
    except Exception as e:
        return jsonify({'code': 500, 'message': str(e), 'data': None}), 500


@shap_bp.route('/dependence', methods=['GET'])
def get_dependence():
    try:
        feature = request.args.get('feature', '月均加班时长')
        model_type = request.args.get('model', 'random_forest')
        result = shap_service.get_dependence(feature, model_type)
        return jsonify({'code': 200, 'message': 'success', 'data': result})
    except Exception as e:
        return jsonify({'code': 500, 'message': str(e), 'data': None}), 500
