import sys
import time
import signal
import argparse

from datetime import datetime

# Note we can import from 'wurker'
from wurker.util import init_logger
logger = init_logger()
wlog = logger.log


def _ping_log(logger, i, log):
    # Log to Wurkzen's logger
    wlog(f"[bees.test_pybee] Ping {i}")

    # Log to the test log
    with open(log, 'a') as fh:
        fh.write(f"{datetime.now()} [bees.test_pybee] Ping {i}\n")


def _interrupt(signum, frame):
    wlog(f"[bees.test_pybee] Interrupted: {signum}")
    sys.exit(1)


def run(duration:int=0, log:str="/tmp/test_pybee.log", interval_seconds:int=10, exit:int=0, **kwargs):
    """
    Wurkzen Wurker Parametric Test PyBee
    ------------------------------------

    Demonstrates several important features as well as acting as a parametric test
    fixture. Has both a 'scheduled' and 'supervised' mode. Enable in `wurker_bee` table.

    Notice that the PyBee may import from any sibling modules, including 'wurker' and
    'settings', which is powerful. A Bee (external script or program) must implement
    an interface and all the libs needed to run independently. A PyBee can use Wurker's
    database connection, models, and any other resources that Wurker has access to,
    and need not run as an independent script.

    But it CAN run independently. This is also demonstrated in this test module.
    By adding a '__main__' block, a PyBee may also have an independent interface,
    while continuing to use Wurker's resources.

    :param duration: How long to run, in seconds. If 0 then poll in 'supervised' mode. (Default: 0)
    :param log: Log test pings with timestamps to this file. (Default: '/tmp/test_pybee.log')
    :param interval_seconds: How often to ping to log file. (Default: 10)
    :param exit: Exit code for the process. If not 0, then also loops before exiting. (Default: 0)
    :param **kwargs: Unused, but included to show that any kwargs are accepted.

    :return: An integer exit code logged by Wurker.

    """

    signal.signal(signal.SIGHUP, _interrupt)
    signal.signal(signal.SIGTERM, _interrupt)

    wlog(f"[bees.test_pybee] Arguments: {duration=}, {interval_seconds=}, {log=}, {exit=}, {kwargs=}")

    if duration > 0:
        wlog("[bees.test_pybee] Scheduled mode")

        for i,_ in enumerate(range(0, duration, interval_seconds)):
            _ping_log(i+1, log)
            time.sleep(interval_seconds)

    else:
        wlog("[bees.test_pybee] Supervised mode")

        i = 0
        while True:
            _ping_log(i, log)
            time.sleep(interval_seconds)
            i += 1


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
