#!/usr/bin/env python3
"""wifisignal - Wi-Fi signal strength from /proc/net/wireless or iw, with fallback.
Usage: wifisignal [--selftest]
  Reads /proc/net/wireless (link quality, signal level in dBm, noise) and
  translates it into a plain-English verdict (Excellent/Good/Fair/Poor) plus
  a bar. Falls back to `iw dev <iface> link` when /proc/net/wireless is
  empty, and says so clearly when there is no Wi-Fi at all instead of
  printing a confusing empty table.
"""
import argparse
import re
import shutil
import subprocess
import sys

SAMPLE = """Inter-| sta-|   Quality        |   Discarded packets               | Missed | WE
 face | tus | link level noise |  nwid  crypt   frag  retry   misc | beacon | 22
  wlan0: 0000   52.  -58.  -96.        0      0      0      0      0        0
"""


def verdict(dbm):
    if dbm is None:
        return "unknown"
    if dbm >= -50:
        return "Excellent"
    if dbm >= -60:
        return "Good"
    if dbm >= -70:
        return "Fair"
    return "Poor"


def bar(quality):
    # quality 0..70 scale in /proc/net/wireless; draw a 10-cell bar
    filled = max(0, min(10, int(round(quality / 70.0 * 10))))
    return "#" * filled + "-" * (10 - filled)


def parse_proc_wireless(text):
    """Return list of dicts: iface, quality, signal_dbm, noise_dbm."""
    out = []
    for line in text.splitlines():
        m = re.match(r"\s*(\S+):\s+\d+\s+(\d+)\.\s+(-?\d+)\.\s+(-?\d+)\.", line)
        if m:
            out.append({"iface": m.group(1), "quality": int(m.group(2)),
                        "signal": int(m.group(3)), "noise": int(m.group(4))})
    return out


def parse_iw_link(text):
    m = re.search(r"signal:\s*(-?\d+)\s*dBm", text)
    return int(m.group(1)) if m else None


def iw_fallback():
    iw = shutil.which("iw")
    if not iw:
        return []
    try:
        devs = subprocess.run([iw, "dev"], capture_output=True, text=True, timeout=5).stdout
    except (subprocess.SubprocessError, OSError):
        return []
    out = []
    for iface in re.findall(r"Interface\s+(\S+)", devs):
        try:
            r = subprocess.run([iw, "dev", iface, "link"], capture_output=True, text=True, timeout=5)
        except (subprocess.SubprocessError, OSError):
            continue
        if "Not connected" in r.stdout:
            continue
        dbm = parse_iw_link(r.stdout)
        if dbm is not None:
            ssid = re.search(r"SSID:\s*(.+)", r.stdout)
            out.append({"iface": iface, "quality": None, "signal": dbm, "noise": None,
                        "ssid": ssid.group(1).strip() if ssid else ""})
    return out


def report(rows):
    print(f"{'INTERFACE':<10} {'SIGNAL':>8} {'NOISE':>7} {'QUALITY':>8}  {'BAR':<10} VERDICT")
    for row in rows:
        sig = f"{row['signal']} dBm" if row.get("signal") is not None else "-"
        noise = f"{row['noise']} dBm" if row.get("noise") is not None else "-"
        qual = f"{row['quality']}/70" if row.get("quality") is not None else "-"
        b = bar(row["quality"]) if row.get("quality") is not None else "----------"
        extra = f"  SSID {row['ssid']}" if row.get("ssid") else ""
        print(f"{row['iface']:<10} {sig:>8} {noise:>7} {qual:>8}  {b:<10} {verdict(row.get('signal'))}{extra}")


def selftest():
    rows = parse_proc_wireless(SAMPLE)
    assert len(rows) == 1 and rows[0]["iface"] == "wlan0" and rows[0]["signal"] == -58, "sample parse failed"
    print("selftest: parsed sample /proc/net/wireless (wlan0, -58 dBm):")
    report(rows)
    assert verdict(-58) == "Good", "verdict wrong"
    print("selftest: verdict for -58 dBm is Good — OK")
    return 0


def main():
    ap = argparse.ArgumentParser(description="wifisignal - Wi-Fi signal strength, with fallback")
    ap.add_argument("--selftest", action="store_true", help="parse an embedded sample /proc/net/wireless")
    args = ap.parse_args()
    if args.selftest:
        return selftest()
    rows = []
    try:
        with open("/proc/net/wireless") as f:
            rows = parse_proc_wireless(f.read())
    except OSError:
        pass
    if not rows:
        rows = iw_fallback()
    if not rows:
        print("wifisignal: no wireless interface found (no entries in /proc/net/wireless, nothing from `iw`).")
        print("This machine may be wired-only or have no Wi-Fi radio.")
        return 0
    report(rows)
    return 0


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