#!/usr/bin/env python3
"""Diagnose RADIUS auth failure on Verona router after RouterOS upgrade."""

import sys
from mikrotik_connect import MikrotikAPI


def section(title):
    print(f"\n{'=' * 70}\n=== {title}\n{'=' * 70}")


def dump(results):
    if not results:
        print("(no results)")
        return
    for r in results:
        for k, v in r.items():
            print(f"  {k}: {v}")
        print("---")


def main():
    api = MikrotikAPI("10.254.254.101", "grahamro",
                     "cFKhz8q5gPLoucMbcT1Iy58r3IXgc3")
    if not api.connect():
        sys.exit(1)
    if not api.login():
        sys.exit(1)

    try:
        section("RouterOS version / identity")
        dump(api.command("/system/resource/print"))
        dump(api.command("/system/routerboard/print"))
        dump(api.command("/system/identity/print"))

        section("RADIUS clients (/radius print detail)")
        dump(api.command("/radius/print"))

        section("RADIUS incoming settings")
        dump(api.command("/radius/incoming/print"))

        section("AAA settings for user logins (/user aaa print)")
        dump(api.command("/user/aaa/print"))

        section("PPP AAA settings (/ppp aaa print)")
        dump(api.command("/ppp/aaa/print"))

        section("PPP profiles (may reference radius)")
        dump(api.command("/ppp/profile/print"))

        section("PPP secrets count")
        secrets = api.command("/ppp/secret/print", ["=count-only="])
        print(secrets)

        section("Active PPP sessions")
        dump(api.command("/ppp/active/print"))

        section("Hotspot servers (if any)")
        dump(api.command("/ip/hotspot/print"))

        section("Recent log messages (last 200)")
        logs = api.command("/log/print")
        # Show only most recent 200 and filter those with radius / auth / ppp
        for entry in logs[-200:]:
            msg = entry.get("message", "")
            topics = entry.get("topics", "")
            time = entry.get("time", "")
            if any(k in (msg + topics).lower() for k in
                   ["radius", "auth", "ppp", "login", "fail", "reject"]):
                print(f"[{time}] {topics}: {msg}")

        section("Certificates (RADIUS over TLS / EAP may need these)")
        dump(api.command("/certificate/print"))

        section("IP services (enabled management services)")
        dump(api.command("/ip/service/print"))

    finally:
        api.disconnect()


if __name__ == "__main__":
    main()
