from fastapi import APIRouter, Depends, HTTPException
from psycopg import AsyncConnection

import app.native.wndb as wndb
from app.infra.db.postgresql.scheme import SchemeRepository
from app.auth.project_dependencies import get_project_pg_connection
from app.services import project_info

router = APIRouter()


async def get_database_connection(
    conn: AsyncConnection = Depends(get_project_pg_connection),
):
    yield conn


@router.get("/scada-info")
async def get_scada_info_with_connection(
    conn: AsyncConnection = Depends(get_database_connection),
):
    """
    使用连接池查询所有SCADA信息
    """
    try:
        _ = conn
        network_name = project_info.name
        scada_data = wndb.get_all_scada_info(network_name) if network_name else []
        return {"success": True, "data": scada_data, "count": len(scada_data)}
    except Exception as e:
        raise HTTPException(
            status_code=500, detail=f"查询SCADA信息时发生错误: {str(e)}"
        )


@router.get("/scheme-list")
async def get_scheme_list_with_connection(
    conn: AsyncConnection = Depends(get_database_connection),
):
    """
    使用连接池查询所有方案信息
    """
    try:
        scheme_data = await SchemeRepository.get_schemes(conn)
        return {"success": True, "data": scheme_data, "count": len(scheme_data)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"查询方案信息时发生错误: {str(e)}")


@router.get("/burst-locate-result")
async def get_burst_locate_result_with_connection(
    conn: AsyncConnection = Depends(get_database_connection),
):
    """
    使用连接池查询所有爆管定位结果
    """
    try:
        burst_data = await SchemeRepository.get_burst_locate_results(conn)
        return {"success": True, "data": burst_data, "count": len(burst_data)}
    except Exception as e:
        raise HTTPException(
            status_code=500, detail=f"查询爆管定位结果时发生错误: {str(e)}"
        )


@router.get("/burst-locate-result/{burst_incident}")
async def get_burst_locate_result_by_incident(
    burst_incident: str,
    conn: AsyncConnection = Depends(get_database_connection),
):
    """
    根据 burst_incident 查询爆管定位结果
    """
    try:
        return await SchemeRepository.get_burst_locate_result_by_incident(
            conn, burst_incident
        )
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"根据 burst_incident 查询爆管定位结果时发生错误: {str(e)}",
        )
