from flask import Blueprint, jsonify, request

from services.jdr_service import jdr_service

jdr_bp = Blueprint('jdr', __name__, url_prefix='/api/jdr')


def log_jdr(route, stage, extra=''):
    message = f'[JDR] route={route} stage={stage}'
    if extra:
        message = f'{message} {extra}'
    print(message, flush=True)


@jdr_bp.route('/dimensions', methods=['GET'])
def get_dimensions():
    log_jdr('/dimensions', 'start')
    try:
        result = jdr_service.get_dimension_scores()
        log_jdr('/dimensions', 'success', f'keys={list(result.keys())}')
        return jsonify({'code': 200, 'message': 'success', 'data': result})
    except Exception as e:
        log_jdr('/dimensions', 'error', f'error={e}')
        return jsonify({'code': 500, 'message': str(e), 'data': None}), 500


@jdr_bp.route('/burnout-engagement', methods=['GET'])
def get_burnout_engagement():
    log_jdr('/burnout-engagement', 'start')
    try:
        result = jdr_service.get_burnout_engagement_analysis()
        log_jdr('/burnout-engagement', 'success', f'keys={list(result.keys())}')
        return jsonify({'code': 200, 'message': 'success', 'data': result})
    except Exception as e:
        log_jdr('/burnout-engagement', 'error', f'error={e}')
        return jsonify({'code': 500, 'message': str(e), 'data': None}), 500


@jdr_bp.route('/path-analysis', methods=['GET'])
def get_path_analysis():
    log_jdr('/path-analysis', 'start')
    try:
        result = jdr_service.get_jdr_path_analysis()
        log_jdr('/path-analysis', 'success', f'keys={list(result.keys())}')
        return jsonify({'code': 200, 'message': 'success', 'data': result})
    except Exception as e:
        log_jdr('/path-analysis', 'error', f'error={e}')
        return jsonify({'code': 500, 'message': str(e), 'data': None}), 500


@jdr_bp.route('/profile', methods=['GET'])
def get_profile():
    dimension = request.args.get('dimension', '所属行业')
    log_jdr('/profile', 'start', f'dimension={dimension}')
    try:
        result = jdr_service.get_jdr_profile(dimension)
        log_jdr('/profile', 'success', f'profiles={len(result.get("profiles", []))}')
        return jsonify({'code': 200, 'message': 'success', 'data': result})
    except Exception as e:
        log_jdr('/profile', 'error', f'dimension={dimension} error={e}')
        return jsonify({'code': 500, 'message': str(e), 'data': None}), 500


@jdr_bp.route('/risk-distribution', methods=['GET'])
def get_risk_distribution():
    log_jdr('/risk-distribution', 'start')
    try:
        result = jdr_service.get_risk_distribution()
        log_jdr('/risk-distribution', 'success', f'total={result.get("total")}')
        return jsonify({'code': 200, 'message': 'success', 'data': result})
    except Exception as e:
        log_jdr('/risk-distribution', 'error', f'error={e}')
        return jsonify({'code': 500, 'message': str(e), 'data': None}), 500
