"""
评测维度管理 API 路由
"""
import os
import pymysql
import yaml
from flask import Blueprint, request, jsonify

# 获取项目根目录
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 创建蓝图
dimension_bp = Blueprint('dimension', __name__, url_prefix='/api/dimension')


def get_db_connection():
    """获取数据库连接"""
    CONFIG_PATH = os.path.join(PROJECT_ROOT, 'config.yaml')
    with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
        CONFIG = yaml.safe_load(f)
    db_config = CONFIG['database']
    return pymysql.connect(
        host=db_config['host'],
        port=db_config['port'],
        user=db_config['username'],
        password=db_config['password'],
        database=db_config['name'],
        charset=db_config.get('charset', 'utf8mb4'),
        cursorclass=pymysql.cursors.DictCursor
    )


def generic_get_all(table_name, order_by='create_time DESC'):
    """通用查询所有"""
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute(f"SELECT * FROM {table_name} ORDER BY {order_by}")
    result = cursor.fetchall()
    cursor.close()
    conn.close()
    return result


def generic_create(table_name, data):
    """通用创建"""
    conn = get_db_connection()
    cursor = conn.cursor()
    columns = ', '.join(data.keys())
    placeholders = ', '.join(['%s'] * len(data))
    sql = f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})"
    cursor.execute(sql, list(data.values()))
    conn.commit()
    new_id = cursor.lastrowid
    cursor.close()
    conn.close()
    return new_id


def generic_update(table_name, id_val, data):
    """通用更新"""
    conn = get_db_connection()
    cursor = conn.cursor()
    set_clause = ', '.join([f"{k} = %s" for k in data.keys()])
    sql = f"UPDATE {table_name} SET {set_clause} WHERE id = %s"
    values = list(data.values()) + [id_val]
    cursor.execute(sql, values)
    conn.commit()
    cursor.close()
    conn.close()


def generic_delete(table_name, id_val):
    """通用删除"""
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute(f"DELETE FROM {table_name} WHERE id = %s", (id_val,))
    conn.commit()
    cursor.close()
    conn.close()


def generic_get_by_id(table_name, id_val):
    """通用按ID查询"""
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute(f"SELECT * FROM {table_name} WHERE id = %s", (id_val,))
    result = cursor.fetchone()
    cursor.close()
    conn.close()
    return result


# ============ 评测维度 CRUD ============

@dimension_bp.route('', methods=['GET'])
def get_dimensions():
    """获取所有评测维度"""
    return jsonify({'code': 0, 'data': generic_get_all('model_dimension')})


@dimension_bp.route('/<int:id>', methods=['GET'])
def get_dimension_by_id(id):
    """获取单个评测维度"""
    dimension = generic_get_by_id('model_dimension', id)
    if dimension:
        return jsonify({'code': 0, 'data': dimension})
    return jsonify({'code': 1, 'message': '维度不存在'})


@dimension_bp.route('', methods=['POST'])
def create_dimension():
    """创建评测维度"""
    data = request.json
    insert_data = {
        'name': data.get('name'),
        'type': data.get('type'),
        'description': data.get('description', '')
    }
    new_id = generic_create('model_dimension', insert_data)
    return jsonify({'code': 0, 'message': '创建成功', 'id': new_id})


@dimension_bp.route('/<int:id>', methods=['PUT'])
def update_dimension(id):
    """更新评测维度"""
    data = request.json
    update_data = {}
    if 'name' in data:
        update_data['name'] = data['name']
    if 'type' in data:
        update_data['type'] = data['type']
    if 'description' in data:
        update_data['description'] = data['description']

    if update_data:
        generic_update('model_dimension', id, update_data)
    return jsonify({'code': 0, 'message': '更新成功'})


@dimension_bp.route('/<int:id>', methods=['DELETE'])
def delete_dimension(id):
    """删除评测维度"""
    generic_delete('model_dimension', id)
    return jsonify({'code': 0, 'message': '删除成功'})
