from fastapi import APIRouter, Request
from typing import Any, List, Dict, Union
from app.services.tjnetwork import (
    Any,
    ChangeSet,
    calculate_demand_to_network,
    calculate_demand_to_nodes,
    calculate_demand_to_region,
    get_demand,
    get_demand_schema,
    set_demand,
)

router = APIRouter()

############################################################
# demand 9.[DEMANDS]
############################################################

@router.get("/getdemandschema")
async def fastapi_get_demand_schema(network: str) -> dict[str, dict[str, Any]]:
    return get_demand_schema(network)


@router.get("/getdemandproperties/")
async def fastapi_get_demand_properties(network: str, junction: str) -> dict[str, Any]:
    return get_demand(network, junction)


# example: set_demand(p, ChangeSet({'junction': 'j1', 'demands': [{'demand': 10.0, 'pattern': None, 'category': 'x'}, {'demand': 20.0, 'pattern': None, 'category': None}]}))
@router.post("/setdemandproperties/", response_model=None)
async def fastapi_set_demand_properties(
    network: str, junction: str, req: Request
) -> ChangeSet:
    props = await req.json()
    ps = {"junction": junction} | props
    return set_demand(network, ChangeSet(ps))

############################################################
# water distribution 36.[Water Distribution]
############################################################
@router.get("/calculatedemandtonodes/")
async def fastapi_calculate_demand_to_nodes(
    network: str, req: Request
) -> dict[str, float]:
    props = await req.json()
    demand = props["demand"]
    nodes = props["nodes"]
    return calculate_demand_to_nodes(network, demand, nodes)

@router.get("/calculatedemandtoregion/")
async def fastapi_calculate_demand_to_region(
    network: str, req: Request
) -> dict[str, float]:
    props = await req.json()
    demand = props["demand"]
    region = props["region"]
    return calculate_demand_to_region(network, demand, region)

@router.get("/calculatedemandtonetwork/")
async def fastapi_calculate_demand_to_network(
    network: str, demand: float
) -> dict[str, float]:
    return calculate_demand_to_network(network, demand)
