from flask import Blueprint, jsonify, request

from services.analysis_service import analysis_service

analysis_bp = Blueprint('analysis', __name__, url_prefix='/api/analysis')


@analysis_bp.route('/importance', methods=['GET'])
def get_importance():
    try:
        model_type = request.args.get('model', 'random_forest')
        result = analysis_service.get_feature_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


@analysis_bp.route('/correlation', methods=['GET'])
def get_correlation():
    try:
        result = analysis_service.get_correlation()
        return jsonify({
            'code': 200,
            'message': 'success',
            'data': result
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500


@analysis_bp.route('/compare', methods=['GET'])
def get_compare():
    try:
        dimension = request.args.get('dimension', 'industry')
        result = analysis_service.get_group_comparison(dimension)
        return jsonify({
            'code': 200,
            'message': 'success',
            'data': result
        })
    except ValueError as e:
        return jsonify({
            'code': 400,
            'message': str(e),
            'data': None
        }), 400
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500
