from fastapi import APIRouter, Request, Depends, Query, Path, Body
from typing import Any, List, Dict, Union
from app.services.tjnetwork import (
    Any,
    get_all_scada_info,
    get_major_node_coords,
    get_major_pipe_nodes,
    get_network_in_extent,
    get_network_link_nodes,
    get_network_node_coords,
    get_node_coord,
)
from app.auth.dependencies import get_current_user as verify_token
from app.infra.cache.redis_client import redis_client, encode_datetime, decode_datetime
import msgpack

router = APIRouter()

############################################################
# coord 24.[COORDINATES]
############################################################

# @router.get("/getcoordschema/")
# async def fastapi_get_coord_schema(network: str) -> dict[str, dict[str, Any]]:
#     return get_coord_schema(network)

# @router.get("/getcoord/")
# async def fastapi_get_coord(network: str, node: str) -> dict[str, Any]:
#     return get_coord(network, node)

# # example: set_coord(p, ChangeSet({'node': 'j1', 'x': 1.0, 'y': 2.0}))
# @router.post("/setcoord/", response_model=None)
# async def fastapi_set_coord(network: str, req: Request) -> ChangeSet:
#     props = await req.json()
#     return set_coord(network, ChangeSet(props))

@router.get(
    "/getnodecoord/",
    summary="获取节点坐标",
    description="获取指定节点的地理坐标(X, Y)"
)
async def fastapi_get_node_coord(
    network: str = Query(..., description="管网名称（或数据库名称）"),
    node: str = Query(..., description="节点ID")
) -> dict[str, float] | None:
    """获取节点的地理坐标信息。"""
    return get_node_coord(network, node)

# Additional geometry queries found in main.py logic (implicit or explicit)
@router.get(
    "/getnetworkinextent/",
    summary="获取范围内的网络元素",
    description="获取指定地理范围内的网络节点和管线"
)
async def fastapi_get_network_in_extent(
    network: str = Query(..., description="管网名称（或数据库名称）"),
    x1: float = Query(..., description="范围左下角X坐标", alias="x1"),
    y1: float = Query(..., description="范围左下角Y坐标", alias="y1"),
    x2: float = Query(..., description="范围右上角X坐标", alias="x2"),
    y2: float = Query(..., description="范围右上角Y坐标", alias="y2")
) -> dict[str, Any]:
    """获取地理范围内的网络几何信息。"""
    return get_network_in_extent(network, x1, y1, x2, y2)

@router.get(
    "/getnetworkgeometries/",
    dependencies=[Depends(verify_token)],
    summary="获取完整网络几何信息",
    description="获取整个水网的所有节点、管线和SCADA点的几何信息(需要身份验证)"
)
async def fastapi_get_network_geometries(
    network: str = Query(..., description="管网名称（或数据库名称）")
) -> dict[str, Any] | None:
    """获取完整的网络几何信息，包括所有节点、管线和SCADA点。结果从缓存返回。"""
    cache_key = f"getnetworkgeometries_{network}"
    data = redis_client.get(cache_key)
    if data:
        loaded_dict = msgpack.unpackb(data, object_hook=decode_datetime)
        return loaded_dict

    coords = get_network_node_coords(network)
    nodes = []
    for node_id, coord in coords.items():
        nodes.append(f"{node_id}:{coord['type']}:{coord['x']}:{coord['y']}")
    links = get_network_link_nodes(network)
    scadas = get_all_scada_info(network)

    results = {"nodes": nodes, "links": links, "scadas": scadas}
    redis_client.set(cache_key, msgpack.packb(results, default=encode_datetime))
    return results

@router.get(
    "/getmajornodecoords/",
    summary="获取主要节点坐标",
    description="获取直径大于等于指定值的节点坐标"
)
async def fastapi_get_majornode_coords(
    network: str = Query(..., description="管网名称（或数据库名称）"),
    diameter: int = Query(..., description="最小直径(mm)", gt=0)
) -> dict[str, dict[str, float]]:
    """获取主要节点的坐标。只返回直径大于等于指定值的节点。"""
    return get_major_node_coords(network, diameter)

@router.get(
    "/getmajorpipenodes/",
    summary="获取主要管道节点",
    description="获取直径大于等于指定值的管道的节点ID"
)
async def fastapi_get_major_pipe_nodes(
    network: str = Query(..., description="管网名称（或数据库名称）"),
    diameter: int = Query(..., description="最小直径(mm)", gt=0)
) -> list[str] | None:
    """获取主要管道节点。只返回直径大于等于指定值的管道。"""
    return get_major_pipe_nodes(network, diameter)

@router.get(
    "/getnetworklinknodes/",
    summary="获取网络管线节点",
    description="获取指定水网所有管线的起点和终点节点"
)
async def fastapi_get_network_link_nodes(
    network: str = Query(..., description="管网名称（或数据库名称）")
) -> list[str] | None:
    """获取网络中所有管线的连接节点。"""
    return get_network_link_nodes(network)

# @router.get("/getallcoords/")
# async def fastapi_get_all_coords(network: str) -> list[Any]:
#     return get_all_coords(network)

# @router.get("/projectcoordinates/")
# async def fastapi_project_coordinates(
#     network: str, from_epsg: int, to_epsg: int
# ) -> ChangeSet:
#     return project_coordinates(network, from_epsg, to_epsg)
