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

Usage: python3 deye_realtime.py [http://deye.local]
  (use the gateway's IP 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": ...}
    (inverter not answering over Modbus).
    """
    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 the inverter state and the battery / PV / load / grid power; returns the exit code."""
    base_url = sys.argv[1] if len(sys.argv) > 1 else "http://deye.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"State:    {realtime['runStateText']}")
    print(f"Battery:  {realtime['batteryVoltage']:.1f} V  {realtime['batteryCurrent']:.1f} A  SOC {realtime['batterySoc']} %")
    print(f"PV:       {realtime['pvPowerTotal']} W")
    print(f"Load:     {realtime['loadPowerTotal']} W")
    print(f"Grid:     {realtime['gridPowerTotal']} W  (positive = importing)")
    return 0


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