#!/usr/bin/env python3
"""netdown - diagnose network health: gateway, DNS, and internet, with a verdict.
Usage: netdown [--host HOST] [--selftest]
  Runs the three checks that actually separate "my Wi-Fi is down" from
  "the site is down": can we reach the default gateway, does DNS resolve,
  and does an HTTP fetch succeed — then gives one verdict naming the
  broken layer, instead of a bare "ping failed". All checks bounded
  (short timeouts); never hangs.
"""
import argparse
import shutil
import socket
import subprocess
import sys
import urllib.request


def default_gateway():
    try:
        with open("/proc/net/route") as f:
            next(f)
            for line in f:
                parts = line.split()
                if len(parts) >= 3 and parts[1] == "00000000":
                    b = bytes.fromhex(parts[2])
                    return ".".join(str(x) for x in reversed(b)), parts[0]
    except OSError:
        pass
    return None, None


def ping(host, count=2, timeout=2):
    ping = shutil.which("ping")
    if not ping:
        return None, "ping command not found"
    try:
        proc = subprocess.run([ping, "-c", str(count), "-W", str(timeout), host],
                              capture_output=True, text=True, timeout=timeout * count + 5)
    except (subprocess.SubprocessError, OSError) as e:
        return None, str(e)
    if proc.returncode == 0:
        import re
        m = re.search(r"rtt min/avg/max/mdev = [\d.]+/([\d.]+)/", proc.stdout)
        return (float(m.group(1)) if m else None), None
    return None, "no reply"


def dns_check(host="example.com"):
    try:
        ip = socket.gethostbyname(host)
        return ip, None
    except socket.gaierror as e:
        return None, str(e)


def http_check(url="http://example.com", timeout=5):
    try:
        req = urllib.request.Request(url, headers={"User-Agent": "netdown/1.0"})
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return resp.status, None
    except Exception as e:
        return None, str(e)


def diagnose():
    results = {}
    gw, gw_iface = default_gateway()
    results["gateway"] = (gw, gw_iface)
    if gw:
        ms, err = ping(gw)
        results["gw_ping"] = (ms, err)
    else:
        results["gw_ping"] = (None, "no default gateway")
    ip, err = dns_check()
    results["dns"] = (ip, err)
    status, err = http_check()
    results["http"] = (status, err)
    return results


def report(results):
    gw, gw_iface = results["gateway"]
    gw_ms, gw_err = results["gw_ping"]
    dns_ip, dns_err = results["dns"]
    http_status, http_err = results["http"]
    print("network diagnosis:")
    print(f"  gateway:  {gw or '(none)'} via {gw_iface or '-'} — "
          f"{f'reachable ({gw_ms:.1f} ms avg)' if gw_ms is not None else 'UNREACHABLE: ' + str(gw_err)}")
    print(f"  DNS:      {'example.com -> ' + str(dns_ip) if dns_ip else 'FAILED: ' + str(dns_err)}")
    print(f"  internet: {'HTTP 200 from example.com' if http_status == 200 else 'FAILED: ' + str(http_err or http_status)}")
    if gw is None or gw_ms is None:
        verdict = "LOCAL NETWORK DOWN — no route to the gateway. Check cable/Wi-Fi and the router."
    elif not dns_ip:
        verdict = "DNS BROKEN — local network works but names do not resolve. Check /etc/resolv.conf and the DNS server."
    elif http_status != 200:
        verdict = "INTERNET DOWN — DNS works but HTTP fails. Check the gateway's upstream / ISP."
    else:
        verdict = "ALL GOOD — gateway, DNS, and internet all working."
    print(f"\nverdict: {verdict}")
    return verdict


def selftest():
    # Bounded local checks: loopback ping + localhost DNS + a local HTTP
    # server, so the selftest proves every check path without the internet.
    import threading
    from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

    class H(BaseHTTPRequestHandler):
        def do_GET(self):
            self.send_response(200)
            self.end_headers()
            self.wfile.write(b"ok")
        def log_message(self, *a):
            pass

    srv = ThreadingHTTPServer(("127.0.0.1", 0), H)
    port = srv.server_address[1]
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    try:
        ms, err = ping("127.0.0.1")
        assert ms is not None, f"loopback ping failed: {err}"
        ip, err = dns_check("localhost")
        assert ip == "127.0.0.1", f"localhost DNS failed: {err}"
        status, err = http_check(f"http://127.0.0.1:{port}/")
        assert status == 200, f"local HTTP failed: {err}"
        print(f"selftest: loopback ping {ms:.1f} ms, localhost DNS -> {ip}, local HTTP {status}")
        gw, _ = default_gateway()
        print(f"selftest: default gateway on this box: {gw or '(none)'}")
        print("selftest: all three check paths work — OK")
        return 0
    finally:
        srv.shutdown()


def main():
    ap = argparse.ArgumentParser(description="netdown - diagnose network health: gateway, DNS, and internet, with a verdict")
    ap.add_argument("--selftest", action="store_true", help="run all three checks against localhost services")
    args = ap.parse_args()
    if args.selftest:
        return selftest()
    results = diagnose()
    report(results)
    gw_ok = results["gw_ping"][0] is not None
    return 0 if gw_ok and results["dns"][0] and results["http"][0] == 200 else 1


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