#!/usr/bin/env python3
"""Forward your own equipment's read-only measurements to ATHENA Repair.

Python 3.9+ standard library only. No charger control or vendor login is performed.
Pair in your ATHENA Repair account first; enter its agent token at the hidden
prompt. The token is never a command-line argument and is stored in a private file.

  python3 athena-repair-agent.py pair --provider ugreen-connect
  python3 athena-repair-agent.py run

UGREEN requires your already-connected local PowerBench bridge. Shelly reads
unauthenticated local Gen2+ RPC meters. POWER-Z requires Linux's powerz hwmon
driver; watts are calculated from measured voltage and current. Shelly/POWER-Z
adapters have fixture tests; their hardware has not been validated for this site.
"""
import argparse
import datetime as dt
import getpass
import ipaddress
import json
import math
import os
from pathlib import Path
import re
import ssl
import stat
import sys
import time
import urllib.error
import urllib.request
import uuid

ENDPOINT = "https://repair.athenalattice.com/api/equipment/ingest"
BRIDGE = "http://127.0.0.1:39028/api/integrations/ugreen"
SCHEMA = "athena.repair.equipment.v1"
PROVIDERS = ("ugreen-connect", "shelly-gen2", "powerz-km003c")
DEFAULT_CONFIG = Path.home() / ".config" / "athena-repair-agent" / "connection.json"
PORT_LABELS = {**{f"C{i}": f"USB-C{i}" for i in range(1, 7)}, "A1": "USB-A1", "DC": "DC"}
RFC1918 = tuple(ipaddress.ip_network(net) for net in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"))


class AgentError(Exception):
    """Safe, user-facing failure; never include token-bearing request objects."""


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise AgentError("A redirect was refused. Use the current agent from ATHENA Repair.")


def utc_now():
    return dt.datetime.now(dt.timezone.utc).isoformat()


def timestamp(value):
    if not isinstance(value, str) or len(value) > 40:
        raise AgentError("The equipment report has no valid source timestamp.")
    try:
        parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
        if parsed.tzinfo is None:
            raise ValueError()
        return parsed.astimezone(dt.timezone.utc).isoformat()
    except (ValueError, OverflowError):
        raise AgentError("The equipment report has no valid source timestamp.") from None


def metric(value, maximum, required=False):
    if value is None and not required:
        return None
    if type(value) not in (int, float) or not math.isfinite(value) or value < 0 or value > maximum:
        raise AgentError("A measurement is invalid or uses unsupported reverse current/power.")
    return float(value)


def local_ipv4(value):
    try:
        address = ipaddress.IPv4Address(value)
    except (ValueError, TypeError):
        raise AgentError("Use the meter's local IPv4 address, without a URL or port.") from None
    if not any(address in network for network in RFC1918):
        raise AgentError("The Shelly adapter requires an explicit private-network IPv4 address.")
    return str(address)


def request_json(url, *, token=None, payload=None):
    # Disable environment proxies and redirects: an agent bearer token may only
    # leave this process in a verified HTTPS request to the fixed Repair endpoint.
    if token is not None and url != ENDPOINT:
        raise AgentError("The agent token can only be sent to ATHENA Repair.")
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect(),
                                        urllib.request.HTTPSHandler(context=ssl.create_default_context()))
    headers = {"Accept": "application/json", "User-Agent": "ATHENA-Repair-Agent/1"}
    data = None
    if payload is not None:
        data = json.dumps(payload, allow_nan=False, separators=(",", ":")).encode("utf-8")
        headers["Content-Type"] = "application/json"
    if token is not None:
        headers["Authorization"] = "Bearer " + token
    try:
        request = urllib.request.Request(url, data=data, headers=headers, method="POST" if data else "GET")
        with opener.open(request, timeout=10) as response:
            raw = response.read(131073)
            if len(raw) > 131072:
                raise AgentError("The equipment service returned an oversized response.")
            result = json.loads(raw)
            if not isinstance(result, dict):
                raise ValueError()
            return result
    except urllib.error.HTTPError as error:
        if error.code in (401, 403):
            raise AgentError("Access was refused. Check your agent pairing or local meter authentication.") from None
        if error.code == 402:
            raise AgentError("Your ATHENA Repair subscription needs attention.") from None
        if error.code == 429:
            raise AgentError("The service is rate-limiting reports. Waiting before retrying is required.") from None
        raise AgentError("The equipment service refused the request (HTTP %d)." % error.code) from None
    except (urllib.error.URLError, TimeoutError, OSError):
        raise AgentError("The equipment service is unreachable. Check its connection and retry.") from None
    except (ValueError, UnicodeError):
        raise AgentError("The equipment service returned an invalid JSON report.") from None


def normalize_ugreen(raw):
    if not isinstance(raw, dict) or raw.get("schema") != "athena.telemetry.charger.v1" or raw.get("read_only") is not True:
        raise AgentError("The local bridge does not expose the supported read-only charger report.")
    if raw.get("connection_state") not in ("connected", "waiting"):
        raise AgentError("Connect your own UGREEN account in your local bridge first.")
    sample = raw.get("sample")
    if not isinstance(sample, dict) or not isinstance(sample.get("ports"), dict) or not 1 <= len(sample["ports"]) <= 16:
        raise AgentError("The local bridge has no valid port report yet.")
    ports = []
    for key, values in sample["ports"].items():
        if not isinstance(key, str) or not re.fullmatch(r"[A-Za-z][A-Za-z0-9]{0,15}", key) or not isinstance(values, dict):
            raise AgentError("The local bridge returned an invalid port.")
        ports.append({"id": key, "label": PORT_LABELS.get(key, key), "watts": metric(values.get("power"), 10000, True),
                      "volts": metric(values.get("voltage"), 1000, True), "amps": metric(values.get("current"), 1000, True)})
    # Only generic model information is forwarded. MAC, serial, vendor account,
    # cloud IDs, firmware data and vendor tokens never enter the outgoing report.
    return {"schema": SCHEMA, "observedAt": timestamp(sample.get("observed_at")),
            "device": {"model": "UGREEN Connect charger"}, "ports": ports}


def normalize_shelly(raw, observed_at=None):
    if not isinstance(raw, dict) or "error" in raw or "code" in raw:
        raise AgentError("This meter does not expose the supported read-only Shelly RPC.")
    ports = []
    for key, values in raw.items():
        if not re.fullmatch(r"(?:switch|pm1|em1):[0-9]{1,3}", key) or not isinstance(values, dict):
            continue
        if values.get("errors"):
            raise AgentError("The Shelly meter reports an error; a fresh reading was not forwarded.")
        watts = metric(values.get("act_power" if key.startswith("em1:") else "apower"), 10000)
        volts, amps = metric(values.get("voltage"), 1000), metric(values.get("current"), 1000)
        if all(value is None for value in (watts, volts, amps)):
            continue
        ports.append({"id": key.replace(":", "_"), "label": "AC " + key, "watts": watts, "volts": volts, "amps": amps})
    if not 1 <= len(ports) <= 32:
        raise AgentError("No supported switch, PM1 or EM1 power-meter channels were found.")
    return {"schema": SCHEMA, "observedAt": timestamp(observed_at or utc_now()),
            "device": {"model": "Shelly local RPC power meter"}, "ports": ports}


def read_powerz(device, root=Path("/sys/class/hwmon")):
    if not isinstance(device, str) or not re.fullmatch(r"hwmon[0-9]{1,5}", device):
        raise AgentError("Choose a Linux powerz hwmon device, such as hwmon3.")
    directory = root / device
    try:
        if (directory / "name").read_text().strip() != "powerz":
            raise AgentError("The selected hwmon entry is not a powerz device.")
        volts = metric(int((directory / "in0_input").read_text()) / 1000.0, 1000, True)
        amps = metric(int((directory / "curr1_input").read_text()) / 1000.0, 1000, True)
    except (OSError, ValueError):
        raise AgentError("Cannot read the Linux powerz sensors. Check the kernel driver and permissions; do not run this agent as root.") from None
    return {"schema": SCHEMA, "observedAt": utc_now(), "device": {"model": "POWER-Z KM003C"},
            "ports": [{"id": "USB", "label": "USB-C (W = V x A)", "volts": volts, "amps": amps, "watts": metric(volts * amps, 10000, True)}]}


def validate_config(config):
    if not isinstance(config, dict) or set(config) - {"version", "providerId", "agentToken", "shellyHost", "powerzDevice"}:
        raise AgentError("The agent configuration format is not supported.")
    if config.get("version") != 1 or config.get("providerId") not in PROVIDERS or not isinstance(config.get("agentToken"), str) or not re.fullmatch(r"athena_agent_[A-Za-z0-9_-]{43}", config["agentToken"]):
        raise AgentError("The agent configuration is incomplete. Pair again in ATHENA Repair.")
    if config["providerId"] == "shelly-gen2":
        local_ipv4(config.get("shellyHost"))
    if config["providerId"] == "powerz-km003c" and not re.fullmatch(r"hwmon[0-9]{1,5}", config.get("powerzDevice", "")):
        raise AgentError("Choose the Linux powerz hwmon device when pairing.")
    return config


def load_config(file):
    try:
        info = file.lstat()
        if not stat.S_ISREG(info.st_mode) or info.st_size > 4096:
            raise AgentError("Use a small, regular private file for the agent configuration.")
        if os.name == "posix" and (info.st_mode & 0o077 or info.st_uid != os.getuid()):
            raise AgentError("The agent configuration must belong to you and allow only your user to read it (chmod 600).")
        return validate_config(json.loads(file.read_text(encoding="utf-8")))
    except (OSError, ValueError, UnicodeError):
        raise AgentError("Cannot read the private agent configuration. Pair your equipment first.") from None


def pair(args):
    file = args.config.expanduser()
    if file.exists() and not args.replace:
        raise AgentError("This computer already has an agent configuration at that path. Use a different --config file, or --replace to replace it.")
    config = {"version": 1, "providerId": args.provider,
              "agentToken": getpass.getpass("Paste the agent token from your ATHENA Repair account (hidden): ").strip()}
    if args.provider == "shelly-gen2":
        config["shellyHost"] = local_ipv4(args.shelly_host)
    if args.provider == "powerz-km003c":
        config["powerzDevice"] = args.powerz_device or ""
    validate_config(config)
    file.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    tmp = file.with_name(file.name + "." + uuid.uuid4().hex + ".tmp")
    try:
        descriptor = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
            json.dump(config, stream, separators=(",", ":"));stream.flush();os.fsync(stream.fileno())
        if not args.replace and file.exists():
            raise AgentError("The configuration path was created while pairing. Try again with another path.")
        os.replace(tmp, file)
    finally:
        try:
            tmp.unlink()
        except FileNotFoundError:
            pass
    print("Pairing saved privately. Run the agent to forward only your equipment's read-only measurements.")


def read_source(config):
    if config["providerId"] == "ugreen-connect":
        return normalize_ugreen(request_json(BRIDGE))
    if config["providerId"] == "shelly-gen2":
        return normalize_shelly(request_json("http://" + local_ipv4(config["shellyHost"]) + "/rpc/Shelly.GetStatus"))
    return read_powerz(config["powerzDevice"])


def run_once(config, last_observed=None, reader=read_source, sender=request_json):
    report = reader(config)
    if report["observedAt"] == last_observed:
        return last_observed, False
    result = sender(ENDPOINT, token=config["agentToken"], payload=report)
    if result.get("accepted") not in (True, False):
        raise AgentError("ATHENA Repair returned an unexpected report acknowledgement.")
    return report["observedAt"], result["accepted"]


def run(args):
    if not 2 <= args.interval <= 300:
        raise AgentError("Choose a report interval between 2 and 300 seconds.")
    config, previous = load_config(args.config.expanduser()), None
    while True:
        started = time.monotonic()
        try:
            previous, accepted = run_once(config, previous)
            print("Read-only report forwarded." if accepted else "Waiting for a newer equipment report.", flush=True)
        except AgentError:
            if args.once:
                raise
            # No request objects, HTTP bodies, token strings or vendor identifiers
            # are included in logs, including on failure.
            print("A report could not be forwarded. Check the connection; retrying in 30 seconds.", file=sys.stderr, flush=True)
            time.sleep(30)
        if args.once:
            return
        time.sleep(max(0.1, args.interval - (time.monotonic() - started)))


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    commands = parser.add_subparsers(dest="command", required=True)
    pairing = commands.add_parser("pair", help="Save an account-owned pairing token using a hidden prompt")
    pairing.add_argument("--provider", choices=PROVIDERS, required=True)
    pairing.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
    pairing.add_argument("--shelly-host", help="Explicit private-network IPv4 address; no URL or port")
    pairing.add_argument("--powerz-device", help="Linux powerz hwmon entry, for example hwmon3")
    pairing.add_argument("--replace", action="store_true", help="Replace the selected existing agent configuration")
    runner = commands.add_parser("run", help="Read measurements and forward them to ATHENA Repair")
    runner.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
    runner.add_argument("--interval", type=float, default=5, help="Seconds between reads (default: 5)")
    runner.add_argument("--once", action="store_true", help="Read and forward at most one source report")
    args = parser.parse_args(argv)
    try:
        pair(args) if args.command == "pair" else run(args)
        return 0
    except AgentError as error:
        print(str(error), file=sys.stderr)
        return 1
    except KeyboardInterrupt:
        return 0


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