#!/usr/bin/env python3
import sys
import subprocess
import urllib.request

# ------------------------------------------------------------
# CONFIG
# ------------------------------------------------------------
PROGRAM_NAME = "babicli"
VERSION = "0.1.0"
# ------------------------------------------------------------


def cmd_netinfo() -> None:
    """Show local and public IP information."""
    print("== Network Information ==")

    # Local IPs (Linux/Raspberry Pi style)
    local_ips_output = subprocess.getoutput("hostname -I").strip()
    local_ips = [ip for ip in local_ips_output.split() if ip]

    print("Local IPs:")
    if local_ips:
        for ip in local_ips:
            print(f"  - {ip}")
    else:
        print("  none")

    # Public IP
    try:
        public_ip = urllib.request.urlopen(
            "https://api.ipify.org",
            timeout=4,
        ).read().decode().strip()
    except Exception:
        public_ip = "Unavailable"

    print(f"Public IP: {public_ip}")


def cmd_update() -> None:
    """
    Show how to update the tool.

    Let pip handle the real update, because this tool is installed
    as a Python package.
    """
    print(f"{PROGRAM_NAME} {VERSION}")
    print()
    print("To update this tool, run:")
    print(f"  pip install --upgrade {PROGRAM_NAME}")


def cmd_help() -> None:
    """Print help text."""
    print(f"""{PROGRAM_NAME} – commandline utility (v{VERSION})

USAGE:
  {PROGRAM_NAME} help
  {PROGRAM_NAME} netinfo
  {PROGRAM_NAME} update

COMMANDS:
  help        Show this help message
  netinfo     Show local + public IP information
  update      Show how to update {PROGRAM_NAME} via pip
""")


def main() -> None:
    """Entry point for the babicli command."""
    if len(sys.argv) < 2:
        cmd_help()
        return

    command = sys.argv[1].lower()

    commands = {
        "help": cmd_help,
        "netinfo": cmd_netinfo,
        "update": cmd_update,
    }

    if command not in commands:
        print(f"Unknown command: {command}")
        print()
        cmd_help()
        return

    commands[command]()


if __name__ == "__main__":
    main()
