#!/usr/bin/env python3
"""JK BMS Web Gateway — read live pack data. Standard library only, no pip installs.

Usage: python3 jkbms_realtime.py [http://jkbms.local]
  (use the gateway's IP, e.g. http://192.168.1.50, if mDNS is not reachable)
"""
import json
import sys
import urllib.request


def fetch_realtime(base_url: str) -> dict:
    """GET /api/realtime and return the decoded JSON.

    Raises on network errors and when the gateway reports {"error": ...}
    (BMS not answering, wrong address, ...).
    """
    with urllib.request.urlopen(f"{base_url}/api/realtime", timeout=5) as response:
        data = json.load(response)
    if "error" in data:
        raise RuntimeError(f"gateway error: {data['error']}")
    return data


def main() -> int:
    """Prints voltage, current, SOC and the cell spread; returns the process exit code."""
    base_url = sys.argv[1] if len(sys.argv) > 1 else "http://jkbms.local"
    try:
        realtime = fetch_realtime(base_url)
    except Exception as ex:  # network, JSON or gateway error: one line, non-zero exit
        print(f"request failed: {ex}", file=sys.stderr)
        return 1

    print(f"Pack voltage: {realtime['totalVoltage']:.2f} V")
    print(f"Current:      {realtime['current']:.2f} A  (positive = charging)")
    print(f"SOC:          {realtime['soc']} %")
    print(f"Cells:        {realtime['minCellVoltage']:.3f} .. {realtime['maxCellVoltage']:.3f} V")
    return 0


if __name__ == "__main__":
    sys.exit(main())
