"""Example: run a RouterOS command and print the result.

Python port of examples/run/main.go.

Usage::

    uv run python -m routeros.examples.run.main --help

    # Basic (plain TCP)
    uv run python -m routeros.examples.run.main \\
        --address 192.168.1.1:8728 \\
        --username admin \\
        --password "" \\
        --command "/system/resource/print"

    # With debug logging
    uv run python -m routeros.examples.run.main --debug \\
        --command "/ip/address/print"

    # Async mode
    uv run python -m routeros.examples.run.main \\
        --async \\
        --command "/interface/print"

    # TLS
    uv run python -m routeros.examples.run.main \\
        --tls \\
        --address 192.168.1.1:8729

    # Multiple words / filters
    uv run python -m routeros.examples.run.main \\
        --command "/ip/address/print ?interface=ether1"
"""

from __future__ import annotations

import argparse
import logging
import ssl
import sys

import routeros


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(
        description="Run a RouterOS command and print the result.",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    p.add_argument("--debug",    action="store_true",            help="Enable DEBUG logging")
    p.add_argument("--address",  default="127.0.0.1:8728",       help="RouterOS address:port")
    p.add_argument("--username", default="admin",                 help="Username")
    p.add_argument("--password", default="",                      help="Password")
    p.add_argument("--command",  default="/system/resource/print",help="RouterOS command (space-separated words)")
    p.add_argument("--async",    dest="use_async", action="store_true", help="Use async mode")
    p.add_argument("--tls",      action="store_true",             help="Use TLS/SSL connection")
    return p


def dial(args: argparse.Namespace, log: logging.Logger) -> routeros.Client:
    if args.tls:
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        return routeros.dial_tls(args.address, args.username, args.password,
                                 tls_context=ctx, logger=log)
    return routeros.dial(args.address, args.username, args.password, logger=log)


def main() -> None:
    args = build_parser().parse_args()

    # Configure logging (mirrors Go's slog handler).
    level = logging.DEBUG if args.debug else logging.INFO
    logging.basicConfig(
        level=level,
        format="%(asctime)s %(levelname)-8s %(name)s  %(message)s",
        datefmt="%Y-%m-%dT%H:%M:%S",
    )
    log = logging.getLogger("routeros")

    # Connect.
    try:
        c = dial(args, log)
    except Exception as exc:
        log.error("could not connect: %s", exc)
        sys.exit(2)

    with c:
        if args.use_async:
            c.async_start()

        # Split the command string into individual API words.
        words = args.command.split()

        try:
            reply = c.run_args(words)
        except routeros.RouterOSError as exc:
            log.error("could not run args: %s", exc)
            sys.exit(2)

        log.info("received %d result(s)", len(reply.re))
        for i, sentence in enumerate(reply.re):
            log.info("result[%d]: %s", i, sentence.map)


if __name__ == "__main__":
    main()
