import psycopg

from app.algorithms.sensor import kmeans as kmeans_sensor
from app.algorithms.sensor import sensitivity
from app.core.config import get_pgconn_string
from app.services.tjnetwork import dump_inp


def pressure_sensor_placement_sensitivity(
    name: str, scheme_name: str, sensor_number: int, min_diameter: int, username: str
) -> None:
    """
    基于改进灵敏度法进行压力监测点优化布置
    :param name: 数据库名称
    :param scheme_name: 监测优化布置方案名称
    :param sensor_number: 传感器数目
    :param min_diameter: 最小管径
    :param username: 用户名
    :return:
    """
    sensor_location = sensitivity.get_ID(
        name=name, sensor_num=sensor_number, min_diameter=min_diameter
    )
    try:
        conn_string = get_pgconn_string(db_name=name)
        with psycopg.connect(conn_string) as conn:
            with conn.cursor() as cur:
                sql = """
                        INSERT INTO sensor_placement (scheme_name, sensor_number, min_diameter, username, sensor_location)
                        VALUES (%s, %s, %s, %s, %s)
                    """

                cur.execute(
                    sql,
                    (
                        scheme_name,
                        sensor_number,
                        min_diameter,
                        username,
                        sensor_location,
                    ),
                )
            conn.commit()
            print("方案信息存储成功！")
    except Exception as e:
        print(f"存储方案信息时出错：{e}")


# 2025/08/21
# 基于kmeans聚类法进行压力监测点优化布置
def pressure_sensor_placement_kmeans(
    name: str, scheme_name: str, sensor_number: int, min_diameter: int, username: str
) -> None:
    """
    基于聚类法进行压力监测点优化布置
    :param name: 数据库名称（注意，此处数据库名称也是inp文件名称，inp文件与pg库名要一样）
    :param scheme_name: 监测优化布置方案名称
    :param sensor_number: 传感器数目
    :param min_diameter: 最小管径
    :param username: 用户名
    :return:
    """
    # dump_inp
    inp_name = f"./db_inp/{name}.db.inp"
    dump_inp(name, inp_name, "2")
    sensor_location = kmeans_sensor.kmeans_sensor_placement(
        name=name, sensor_num=sensor_number, min_diameter=min_diameter
    )
    try:
        conn_string = get_pgconn_string(db_name=name)
        with psycopg.connect(conn_string) as conn:
            with conn.cursor() as cur:
                sql = """
                        INSERT INTO sensor_placement (scheme_name, sensor_number, min_diameter, username, sensor_location)
                        VALUES (%s, %s, %s, %s, %s)
                    """

                cur.execute(
                    sql,
                    (
                        scheme_name,
                        sensor_number,
                        min_diameter,
                        username,
                        sensor_location,
                    ),
                )
            conn.commit()
            print("方案信息存储成功！")
    except Exception as e:
        print(f"存储方案信息时出错：{e}")
