from fastapi import APIRouter
from psycopg2.extras import RealDictCursor
from database import get_db_connection
from schemas import MetricCreate

router = APIRouter()

@router.get("/api/metrics")
def get_metrics():
    conn = get_db_connection()
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    cursor.execute("SELECT * FROM tb_metric_dict ORDER BY category_level_1, metric_id")
    metrics = cursor.fetchall()
    cursor.close()
    conn.close()
    return {"status": "success", "data": metrics}

@router.post("/api/metrics")
def create_metric(item: MetricCreate):
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute(
        "INSERT INTO tb_metric_dict (category_level_1, category_level_2, metric_name, value_type, description) VALUES (%s, %s, %s, %s, %s)", 
        (item.category_level_1, item.category_level_2, item.metric_name, item.value_type, item.description)
    )
    conn.commit()
    cursor.close()
    conn.close()
    return {"status": "success", "message": "指标添加成功！"}

@router.put("/api/metrics/{metric_id}")
def update_metric(metric_id: int, item: MetricCreate):
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute(
        "UPDATE tb_metric_dict SET category_level_1 = %s, category_level_2 = %s, metric_name = %s, value_type = %s, description = %s WHERE metric_id = %s", 
        (item.category_level_1, item.category_level_2, item.metric_name, item.value_type, item.description, metric_id)
    )
    conn.commit()
    cursor.close()
    conn.close()
    return {"status": "success", "message": "指标修改成功！"}

@router.delete("/api/metrics/{metric_id}")
def delete_metric(metric_id: int):
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("DELETE FROM tb_metric_dict WHERE metric_id = %s", (metric_id,))
    conn.commit()
    cursor.close()
    conn.close()
    return {"status": "success", "message": "指标删除成功！"}
