#!/usr/bin/env python3
"""mesh — the whole mesh on one screen, in plain lines.

Reads the same feed the Security Center MESH page reads:
    http://192.168.8.166:7077/mesh_page.json

Prints every node's state, the door codes, and the uptime
forecasts. Works only on home Wi-Fi.

Use:  mesh
"""

import json
import sys
import urllib.request

FEED_URL = "http://192.168.8.166:7077/mesh_page.json"


def get_feed():
    request = urllib.request.Request(
        FEED_URL, headers={"User-Agent": "777-mesh/7.7 (iSH)"}
    )
    with urllib.request.urlopen(request, timeout=6) as page:
        return json.loads(page.read().decode("utf-8", errors="replace"))


def node_rows(feed):
    """Nodes can be a list of entries, or a name->info book."""
    nodes = feed.get("nodes") or []
    if isinstance(nodes, dict):
        return [(name, info) for name, info in sorted(nodes.items())]
    rows = []
    for node in nodes:
        if isinstance(node, dict):
            rows.append((node.get("name", "?"), node))
    return rows


def node_state(info):
    if isinstance(info, dict):
        return info.get("state") or info.get("status") or "?"
    return str(info)


def door_lines(feed):
    doors = feed.get("doors") or []
    lines = []
    if isinstance(doors, dict):
        doors = [
            {"name": name, **info} if isinstance(info, dict) else {"name": name, "code": info}
            for name, info in doors.items()
        ]
    for door in doors:
        if isinstance(door, dict):
            name = door.get("name") or door.get("url") or "?"
            code = door.get("code") or door.get("status") or "?"
            lines.append("%-28s %s" % (name, code))
    return lines


def forecast_lines(feed):
    for key in ("projections", "forecasts", "forecast"):
        items = feed.get(key)
        if isinstance(items, list) and items:
            return [str(item) for item in items]
        if isinstance(items, str) and items:
            return [items]
    return []


def main():
    try:
        feed = get_feed()
    except Exception:
        print("Could not reach the house box.")
        print("This tool only works on home Wi-Fi.")
        print("Check the iPad is on the house Wi-Fi, then try again.")
        return 1

    print("THE MESH")
    print("--------")
    rows = node_rows(feed)
    if not rows:
        print("The feed came back, but no nodes were listed in it.")
    for name, info in rows:
        print("%-22s %s" % (name, node_state(info)))

    doors = door_lines(feed)
    if doors:
        print("")
        print("DOORS")
        print("-----")
        for line in doors:
            print(line)

    forecasts = forecast_lines(feed)
    if forecasts:
        print("")
        print("UPTIME FORECAST")
        print("---------------")
        for line in forecasts:
            print(line)
    return 0


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