#!/usr/bin/env python3
"""guards — the Flint3 guard board, in plain lines.

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

Works only on home Wi-Fi. Off the home network it says so,
plain and simple, and stops.

Use:  guards
"""

import json
import sys
import urllib.request

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


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


def guard_rows(feed):
    """The feed's guards can be a name->info book, or a list."""
    guards = feed.get("guards") or {}
    if isinstance(guards, dict):
        return sorted(guards.items())
    if isinstance(guards, list):
        return [(g.get("name", "?"), g) for g in guards if isinstance(g, dict)]
    return []


def alert_lines(feed, rows):
    """Collect alert text from wherever the feed keeps it."""
    found = []
    for key in ("alerts", "high_alerts"):
        items = feed.get(key)
        if isinstance(items, list):
            found.extend(str(item) for item in items)
    for _name, info in rows:
        if isinstance(info, dict) and info.get("alert"):
            found.append(str(info["alert"]))
    return found


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

    rows = guard_rows(feed)
    print("FLINT3 GUARDS")
    print("-------------")
    if not rows:
        print("The feed came back, but no guards were listed in it.")
    for name, info in rows:
        status = info.get("status", "?") if isinstance(info, dict) else "?"
        print("%-22s %s" % (name, status))

    alerts = alert_lines(feed, rows)
    high = [a for a in alerts if "HIGH" in a.upper()]
    print("")
    if high:
        print("HIGH ALERTS:")
        for line in high:
            print("  !", line)
    elif alerts:
        print("Alerts (none HIGH): %d" % len(alerts))
    else:
        print("No alerts in the feed. All quiet.")
    return 0


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