import argparse
import asyncio
import contextlib
import pathlib
import sys

from rabdomancia.controller import RabdomanciaController


async def main(**kwargs):
    """Start rabdomancia graphics and sound.

    If you DNS inputs in real-time from your network to rabdomancia, it will
    produce a visualisation with accompanying sound.
    """

    rc = RabdomanciaController(**kwargs)

    if not (rc.raw_input or rc.lists_loaded):
        sys.stderr.write("""
WARNING: lists have not been initialised, this probably means you haven't
         imported them. Try running import-lists.sh!

         rabdomancia will work, but clusters won't be ideal.

""")
    await rc.run_forever()


def run():
    parser = argparse.ArgumentParser(description=main.__doc__)
    # input settings
    input_group = parser.add_argument_group("Input settings")
    input_group.add_argument(
        "--disable-dnstap",
        action="store_true",
        help="If present, stdin will be used instead of a DNSTAP listener",
    )
    input_group.add_argument(
        "--raw-input",
        action="store_true",
        help="If present, the received input will be used verbatim "
        "(if using DNSTAP, only the right-most TLD will be added). "
        "Otherwise, the system will complete information using public TLDs "
        "registries, domain lists, and counters",
    )
    input_group.add_argument(
        "--domain-lists-dir",
        type=pathlib.Path,
        default=pathlib.Path("domain-lists"),
        help="Where to find the domain lists, as generated by import-lists.sh",
    )
    # DNSTAP settings
    dnstap_group = parser.add_argument_group("DNSTAP settings")
    dnstap_group.add_argument("--host", default="")
    dnstap_group.add_argument("--port", default=5342, type=int)
    # graphic / gource settings
    graphic_group = parser.add_argument_group("Graphic / gource settings")
    graphic_group.add_argument("--bloom-multiplier", type=float, default=2.0)
    graphic_group.add_argument("--bloom-intensity", type=float, default=0.2)
    graphic_group.add_argument("--elasticity", type=float, default=0.5)
    graphic_group.add_argument("--dir-name-position", type=float, default=0.9)
    graphic_group.add_argument("--logo", type=pathlib.Path, default=pathlib.Path("logo.png"))
    # sound settings
    sound_group = parser.add_argument_group("Sound settings")
    sound_group.add_argument("--player", type=str, default="mpv")

    ns = parser.parse_args()

    with contextlib.suppress(KeyboardInterrupt):
        asyncio.run(main(**vars(ns)))


if __name__ == "__main__":
    run()
