# Run with Python 3: python3 water-pipe.py
# Uses the standard library. SI inputs; horizontal straight pipe without fittings.
import json
import sys
import urllib.error
import urllib.request

ENDPOINT = "https://www.engivault.com/api/hydraulics/water-pipe-loss"

def calculate(temperature):
    payload = {
        "temperature": temperature, "inletPressure": 200000,
        "flowRate": 0.001, "length": 20, "diameter": 0.025,
        "roughness": 0.000015,
    }
    request = urllib.request.Request(
        ENDPOINT, data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json"}, method="POST",
    )
    try:
        with urllib.request.urlopen(request, timeout=15) as response:
            result = json.load(response)
    except urllib.error.HTTPError as error:
        try:
            message = json.load(error).get("error", str(error))
        except (ValueError, AttributeError):
            message = str(error)
        raise RuntimeError(message) from error
    if not result.get("success"):
        raise RuntimeError(result.get("error", "Calculation failed"))
    return result["data"]

if __name__ == "__main__":
    try:
        for temperature in (20, 80):
            result = calculate(temperature)
            print(f"{temperature} C: {result['pressureDrop'] / 1000:.2f} kPa")
    except (RuntimeError, urllib.error.URLError, TimeoutError, ValueError) as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
