from fastapi import APIRouter, Request
from typing import Any, List, Dict, Union
from app.services.tjnetwork import (
    Any,
    ChangeSet,
    add_pump,
    delete_pump,
    get_all_pumps,
    get_pump,
    get_pump_schema,
    set_pump,
)

router = APIRouter()

@router.get("/getpumpschema")
async def fastapi_get_pump_schema(network: str) -> dict[str, dict[str, Any]]:
    return get_pump_schema(network)

@router.post("/addpump/", response_model=None)
async def fastapi_add_pump(
    network: str, pump: str, node1: str, node2: str, power: float = 0.0
) -> ChangeSet:
    ps = {"id": pump, "node1": node1, "node2": node2, "power": power}
    return add_pump(network, ChangeSet(ps))

@router.post("/deletepump/", response_model=None)
async def fastapi_delete_pump(network: str, pump: str) -> ChangeSet:
    ps = {"id": pump}
    return delete_pump(network, ChangeSet(ps))

@router.get("/getpumpnode1/")
async def fastapi_get_pump_node1(network: str, pump: str) -> str | None:
    ps = get_pump(network, pump)
    return ps["node1"]

@router.get("/getpumpnode2/")
async def fastapi_get_pump_node2(network: str, pump: str) -> str | None:
    ps = get_pump(network, pump)
    return ps["node2"]

@router.post("/setpumpnode1/", response_model=None)
async def fastapi_set_pump_node1(network: str, pump: str, node1: str) -> ChangeSet:
    ps = {"id": pump, "node1": node1}
    return set_pump(network, ChangeSet(ps))

@router.post("/setpumpnode2/", response_model=None)
async def fastapi_set_pump_node2(network: str, pump: str, node2: str) -> ChangeSet:
    ps = {"id": pump, "node2": node2}
    return set_pump(network, ChangeSet(ps))

@router.get("/getpumpproperties/")
async def fastapi_get_pump_properties(network: str, pump: str) -> dict[str, Any]:
    return get_pump(network, pump)

@router.get("/getallpumpproperties/")
async def fastapi_get_all_pump_properties(network: str) -> list[dict[str, Any]]:
    # 缓存查询结果提高性能
    # global redis_client
    results = get_all_pumps(network)
    return results

@router.post("/setpumpproperties/", response_model=None)
async def fastapi_set_pump_properties(
    network: str, pump: str, req: Request
) -> ChangeSet:
    props = await req.json()
    ps = {"id": pump} | props
    return set_pump(network, ChangeSet(ps))
