from flask import Blueprint, jsonify, request
from lib.db import execute_query, execute_update
from lib.doris_optimize import get_pool, optimize_doris_table, get_doris_table_stats
import json

global_config_api = Blueprint('global_config_api', __name__)


@global_config_api.route('/api/global-config/sum-data-fields', methods=['GET'])
def get_sum_data_fields():
    """获取求和数据采集字段配置"""
    try:
        result = execute_query("SELECT sum_data_fields FROM t_daily_report_global_config WHERE id = 1")
        if result and result[0]['sum_data_fields']:
            fields = json.loads(result[0]['sum_data_fields'])
            return jsonify({'success': True, 'data': fields})
        return jsonify({'success': True, 'data': []})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500


@global_config_api.route('/api/global-config/sum-data-fields', methods=['POST'])
def save_sum_data_fields():
    """保存求和数据采集字段配置"""
    try:
        data = request.get_json()
        fields = data.get('sum_data_fields', [])
        fields_json = json.dumps(fields)
        
        execute_update(
            "UPDATE t_daily_report_global_config SET sum_data_fields = %s, update_time = NOW() WHERE id = 1",
            (fields_json,)
        )
        
        return jsonify({'success': True, 'message': '配置保存成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500


# ==================== Doris 优化接口 ====================

@global_config_api.route('/api/doris/status', methods=['GET'])
def get_doris_status():
    """获取 Doris 连接池状态"""
    try:
        pool = get_pool()
        stats = pool.get_stats()
        return jsonify({'success': True, 'data': stats})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500


@global_config_api.route('/api/doris/optimize-table', methods=['POST'])
def api_optimize_table():
    """优化 Doris 表统计信息"""
    try:
        data = request.get_json()
        table_name = data.get('table_name', '')
        
        if not table_name:
            return jsonify({'success': False, 'message': '请提供表名'}), 400
        
        result = optimize_doris_table(table_name)
        if result:
            return jsonify({'success': True, 'message': f'表 {table_name} 优化成功'})
        else:
            return jsonify({'success': False, 'message': f'表 {table_name} 优化失败'})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500


@global_config_api.route('/api/doris/table-stats', methods=['GET'])
def api_get_table_stats():
    """获取 Doris 表统计信息"""
    try:
        table_name = request.args.get('table_name', 't_daily_report_sum_data')
        stats = get_doris_table_stats(table_name)
        return jsonify({'success': True, 'data': stats})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500


@global_config_api.route('/api/doris/health-check', methods=['GET'])
def doris_health_check():
    """Doris 健康检查"""
    try:
        # 简单查询测试连接
        result = execute_query('SELECT 1 as test')
        return jsonify({
            'success': True,
            'status': 'healthy',
            'test_query': result
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'status': 'unhealthy',
            'message': str(e)
        }), 500