from flask import Blueprint, jsonify, request

from services.cluster_service import cluster_service

cluster_bp = Blueprint('cluster', __name__, url_prefix='/api/cluster')


@cluster_bp.route('/result', methods=['GET'])
def get_result():
    try:
        n_clusters = request.args.get('n_clusters', 3, type=int)
        n_clusters = max(2, min(10, n_clusters))
        
        result = cluster_service.get_cluster_result(n_clusters)
        return jsonify({
            'code': 200,
            'message': 'success',
            'data': result
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500


@cluster_bp.route('/profile', methods=['GET'])
def get_profile():
    try:
        n_clusters = request.args.get('n_clusters', 3, type=int)
        n_clusters = max(2, min(10, n_clusters))
        
        result = cluster_service.get_cluster_profile(n_clusters)
        return jsonify({
            'code': 200,
            'message': 'success',
            'data': result
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500


@cluster_bp.route('/scatter', methods=['GET'])
def get_scatter():
    try:
        n_clusters = request.args.get('n_clusters', 3, type=int)
        x_axis = request.args.get('x_axis', '月均加班时长')
        y_axis = request.args.get('y_axis', '缺勤时长（小时）')
        
        n_clusters = max(2, min(10, n_clusters))
        
        result = cluster_service.get_scatter_data(n_clusters, x_axis, y_axis)
        return jsonify({
            'code': 200,
            'message': 'success',
            'data': result
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500
