#    Copyright (C) 2015 Yahoo! Inc. All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
from __future__ import annotations

import collections
import fractions
import functools
import heapq
import inspect
import logging
import math
import random
import threading
from collections.abc import Callable, Generator, Iterable
from typing import Any, ParamSpec, NamedTuple, TypeVar, TYPE_CHECKING

from concurrent import futures

try:
    import prettytable
except ImportError:
    prettytable = None  # type: ignore[assignment]

import futurist
from futurist import _utils as utils

if TYPE_CHECKING:
    from logging import Logger

LOG = logging.getLogger(__name__)

_P = ParamSpec('_P')
_R = TypeVar('_R')


class NeverAgain(Exception):
    """Exception to raise to stop further periodic calls for a function.

    When you want a function never run again you can throw this from
    you periodic function and that will signify to the execution framework
    to remove that function (and never run it again).
    """


_REQUIRED_ATTRS = (
    '_is_periodic',
    '_periodic_spacing',
    '_periodic_run_immediately',
)

_DEFAULT_COLS = (
    'Name',
    'Active',
    'Periodicity',
    'Runs in',
    'Runs',
    'Failures',
    'Successes',
    'Stop Requested',
    'Average elapsed',
    'Average elapsed waiting',
)

# Constants that are used to determine what 'kind' the current callback
# is being ran as.
PERIODIC = 'periodic'
IMMEDIATE = 'immediate'


class Work(NamedTuple):
    """Named unit of work that can be periodically scheduled and watched."""

    name: str
    callback: Callable[..., Any]
    args: tuple[Any, ...]
    kwargs: dict[str, Any]

    def __call__(self) -> Any:
        return self.callback(*self.args, **self.kwargs)


_Metrics = dict[str, int | float | bool]


class Watcher:
    """A **read-only** object representing a periodic callback's activities."""

    def __init__(self, metrics: _Metrics, work: Work) -> None:
        self._metrics = metrics
        self._work = work

    def __repr__(self) -> str:
        return (
            f"<Watcher(metrics={self._metrics}, work={self._work}) "
            f"object at 0x{id(self):x}>"
        )

    @property
    def requested_stop(self) -> bool:
        """If the work unit being ran has requested to be stopped."""
        return bool(self._metrics['requested_stop'])

    @property
    def work(self) -> Work:
        """**Read-only** named work tuple this object watches."""
        return self._work

    @property
    def runs(self) -> int:
        """How many times the periodic callback has been ran."""
        return int(self._metrics['runs'])

    @property
    def successes(self) -> int:
        """How many times the periodic callback ran successfully."""
        return int(self._metrics['successes'])

    @property
    def failures(self) -> int:
        """How many times the periodic callback ran unsuccessfully."""
        return int(self._metrics['failures'])

    @property
    def elapsed(self) -> float:
        """Total amount of time the periodic callback has ran for."""
        return float(self._metrics['elapsed'])

    @property
    def elapsed_waiting(self) -> float:
        """Total amount of time the periodic callback has waited to run for."""
        return float(self._metrics['elapsed_waiting'])

    @property
    def average_elapsed_waiting(self) -> float:
        """Avg. amount of time the periodic callback has waited to run for.

        This may raise a ``ZeroDivisionError`` if there has been no runs.
        """
        return float(self._metrics['elapsed_waiting']) / int(
            self._metrics['runs']
        )

    @property
    def average_elapsed(self) -> float:
        """Avg. amount of time the periodic callback has ran for.

        This may raise a ``ZeroDivisionError`` if there has been no runs.
        """
        return float(self._metrics['elapsed']) / int(self._metrics['runs'])


def _check_attrs(obj: Any) -> list[str]:
    """Checks that a periodic function/method has all the expected attributes.

    This will return the expected attributes that were **not** found.
    """
    missing_attrs: list[str] = []
    for attr_name in _REQUIRED_ATTRS:
        if not hasattr(obj, attr_name):
            missing_attrs.append(attr_name)
    return missing_attrs


def is_periodic(obj: Any) -> bool:
    """Check whether an object is a valid periodic callable.

    :param obj: object to inspect
    :type obj: anything
    :return: True if obj is a periodic task, otherwise False
    """
    return callable(obj) and not _check_attrs(obj)


def periodic(
    spacing: float | int, run_immediately: bool = False, enabled: bool = True
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
    """Tags a method/function as wanting/able to execute periodically.

    :param spacing: how often to run the decorated function (required)
    :type spacing: float/int
    :param run_immediately: option to specify whether to run
                            immediately or wait until the spacing provided has
                            elapsed before running for the first time
    :type run_immediately: boolean
    :param enabled: whether the task is enabled to run
    :type enabled: boolean
    """

    if spacing <= 0 and enabled:
        raise ValueError(
            "Periodicity/spacing must be greater than"
            f" zero instead of {spacing}"
        )

    def wrapper(f: Callable[_P, _R]) -> Callable[_P, _R]:
        f._is_periodic = enabled  # type: ignore[attr-defined]
        f._periodic_spacing = spacing  # type: ignore[attr-defined]
        f._periodic_run_immediately = run_immediately  # type: ignore[attr-defined]

        @functools.wraps(f)
        def decorator(*args: _P.args, **kwargs: _P.kwargs) -> _R:
            return f(*args, **kwargs)

        return decorator

    return wrapper


_ScheduleStrategy = Callable[
    [Callable[..., Any], float, float, _Metrics], float
]
_InitialScheduleStrategy = Callable[[Callable[..., Any], float], float]


def _add_jitter(
    max_percent_jitter: float | fractions.Fraction,
) -> Callable[[_ScheduleStrategy], _ScheduleStrategy]:
    """Wraps a existing strategy and adds jitter to it.

    0% to 100% of the spacing value will be added to this value to ensure
    callbacks do not synchronize.
    """
    if max_percent_jitter > 1 or max_percent_jitter < 0:
        raise ValueError(
            "Invalid 'max_percent_jitter', must be greater or"
            " equal to 0.0 and less than or equal to 1.0"
        )

    def wrapper(func: _ScheduleStrategy) -> _ScheduleStrategy:
        rnd = random.SystemRandom()

        @functools.wraps(func)
        def decorator(
            cb: Callable[..., Any],
            started_at: float,
            finished_at: float,
            metrics: _Metrics,
        ) -> float:
            next_run = func(cb, started_at, finished_at, metrics)
            how_often: float = cb._periodic_spacing  # type: ignore[attr-defined]
            jitter = how_often * (rnd.random() * float(max_percent_jitter))
            return next_run + jitter

        decorator.__name__ += "_with_jitter"
        return decorator

    return wrapper


def _last_finished_strategy(
    cb: Callable[..., Any],
    started_at: float,
    finished_at: float,
    metrics: _Metrics,
) -> float:
    # Determine when the callback should next run based on when it was
    # last finished **only** given metrics about this information.
    how_often: float = cb._periodic_spacing  # type: ignore[attr-defined]
    return finished_at + how_often


def _last_started_strategy(
    cb: Callable[..., Any],
    started_at: float,
    finished_at: float,
    metrics: _Metrics,
) -> float:
    # Determine when the callback should next run based on when it was
    # last started **only** given metrics about this information.
    how_often: float = cb._periodic_spacing  # type: ignore[attr-defined]
    return started_at + how_often


def _aligned_last_finished_strategy(
    cb: Callable[..., Any],
    started_at: float,
    finished_at: float,
    metrics: _Metrics,
) -> float:
    # Determine when the callback should next run based on when it was
    # last finished **only** where the last finished time is first aligned to
    # be a multiple of the expected spacing (so that no matter how long or
    # how short the callback takes it is always ran on its next aligned
    # to spacing time).
    how_often: float = cb._periodic_spacing  # type: ignore[attr-defined]
    aligned_finished_at = finished_at - math.fmod(finished_at, how_often)
    return aligned_finished_at + how_often


def _now_plus_periodicity(cb: Callable[..., Any], now: float) -> float:
    how_often: float = cb._periodic_spacing  # type: ignore[attr-defined]
    return how_often + now


class _Schedule:
    """Internal heap-based structure that maintains the schedule/ordering.

    This stores a heap composed of the following ``(next_run, index)`` where
    ``next_run`` is the next desired runtime for the callback that is stored
    somewhere with the index provided. The index is saved so that if two
    functions with the same ``next_run`` time are inserted, that the one with
    the smaller index is preferred (it is also saved so that on pop we can
    know what the index of the callback we should call is).
    """

    def __init__(self) -> None:
        self._ordering: list[tuple[float, int]] = []

    def push(self, next_run: float, index: int) -> None:
        heapq.heappush(self._ordering, (next_run, index))

    def __len__(self) -> int:
        return len(self._ordering)

    def fetch_next_run(self, index: int) -> float | None:
        for next_run, a_index in self._ordering:
            if a_index == index:
                return next_run
        return None

    def pop(self) -> tuple[float, int]:
        return heapq.heappop(self._ordering)


def _on_failure_log(
    log: Logger,
    cb: Callable[..., Any],
    kind: str,
    spacing: float,
    exc_info: utils.ExcInfoT,
    traceback: str | None = None,
) -> None:
    cb_name = utils.get_callback_name(cb)
    if all(exc_info) or not traceback:
        log.error(
            "Failed to call %s '%s' (it runs every %0.2f seconds)",
            kind,
            cb_name,
            spacing,
            exc_info=exc_info,  # type: ignore[arg-type]
        )
    else:
        log.error(
            "Failed to call %s '%s' (it runs every %0.2f seconds):\n%s",
            kind,
            cb_name,
            spacing,
            traceback,
        )


class _Runner:
    def __init__(
        self,
        now_func: Callable[[], float],
        retain_traceback: bool = True,
    ) -> None:
        self.now_func = now_func
        self.retain_traceback = retain_traceback

    def run(self, work: Work) -> tuple[float, float, utils.Failure | None]:
        failure = None
        started_at = self.now_func()
        try:
            work()
        except Exception:
            # Until https://bugs.python.org/issue24451 is merged we have to
            # capture and return the failure, so that we can have reliable
            # timing information.
            failure = utils.Failure(self.retain_traceback)
        finished_at = self.now_func()
        return (started_at, finished_at, failure)


def _build(
    now_func: Callable[[], float],
    works: list[Work],
    next_run_scheduler: _InitialScheduleStrategy,
) -> tuple[collections.deque[int], _Schedule]:
    schedule = _Schedule()
    now: float | None = None
    immediates: collections.deque[int] = collections.deque()
    for index, work in enumerate(works):
        cb = work.callback
        if cb._periodic_run_immediately:  # type: ignore[attr-defined]
            immediates.append(index)
        else:
            if now is None:
                now = now_func()
            next_run = next_run_scheduler(cb, now)
            schedule.push(next_run, index)
    return immediates, schedule


_SCHEDULE_RETRY_EXCEPTIONS = (RuntimeError, futurist.RejectedSubmission)


class ExecutorFactory:
    """Base class for any executor factory."""

    shutdown: bool = True
    """Whether the executor should be shut down on periodic worker stop."""

    def __call__(self) -> futures.Executor:
        """Return the executor to be used."""
        raise NotImplementedError()


class ExistingExecutor(ExecutorFactory):
    """An executor factory returning the existing object."""

    def __init__(
        self, executor: futures.Executor, shutdown: bool = False
    ) -> None:
        self._executor = executor
        self.shutdown = shutdown

    def __call__(self) -> futures.Executor:
        return self._executor


_OnFailureCallback = Callable[..., None]


class PeriodicWorker:
    """Calls a collection of callables periodically (sleeping as needed...).

    NOTE(harlowja): typically the :py:meth:`.start` method is executed in a
    background thread so that the periodic callables are executed in
    the background/asynchronously (using the defined periods to determine
    when each is called).
    """

    #: Max amount of time to wait when running (forces a wakeup when elapsed).
    MAX_LOOP_IDLE: float = 30

    _NO_OP_ARGS: tuple[Any, ...] = ()
    _NO_OP_KWARGS: dict[str, Any] = {}
    _INITIAL_METRICS: _Metrics = {
        'runs': 0,
        'elapsed': 0,
        'elapsed_waiting': 0,
        'failures': 0,
        'successes': 0,
        'requested_stop': False,
    }

    # When scheduling fails temporary, use a random delay between 0.9-1.1 sec.
    _RESCHEDULE_DELAY: float = 0.9
    _RESCHEDULE_JITTER: float = 0.2

    DEFAULT_JITTER: fractions.Fraction = fractions.Fraction(5, 100)
    """
    Default jitter percentage the built-in strategies (that have jitter
    support) will use.
    """

    BUILT_IN_STRATEGIES: dict[
        str, tuple[_ScheduleStrategy, _InitialScheduleStrategy]
    ] = {
        'last_started': (
            _last_started_strategy,
            _now_plus_periodicity,
        ),
        'last_started_jitter': (
            _add_jitter(DEFAULT_JITTER)(_last_started_strategy),
            _now_plus_periodicity,
        ),
        'last_finished': (
            _last_finished_strategy,
            _now_plus_periodicity,
        ),
        'last_finished_jitter': (
            _add_jitter(DEFAULT_JITTER)(_last_finished_strategy),
            _now_plus_periodicity,
        ),
        'aligned_last_finished': (
            _aligned_last_finished_strategy,
            _now_plus_periodicity,
        ),
        'aligned_last_finished_jitter': (
            _add_jitter(DEFAULT_JITTER)(_aligned_last_finished_strategy),
            _now_plus_periodicity,
        ),
    }
    """
    Built in scheduling strategies (used to determine when next to run
    a periodic callable).

    The first element is the strategy to use after the initial start
    and the second element is the strategy to use for the initial start.

    These are made somewhat pluggable so that we can *easily* add-on
    different types later (perhaps one that uses a cron-style syntax
    for example).
    """

    @classmethod
    def create(
        cls,
        objects: Iterable[Any],
        exclude_hidden: bool = True,
        log: Logger | None = None,
        executor_factory: ExecutorFactory
        | Callable[[], futures.Executor]
        | None = None,
        cond_cls: type[threading.Condition] = threading.Condition,
        event_cls: type[threading.Event] = threading.Event,
        schedule_strategy: str = 'last_started',
        now_func: Callable[[], float] = utils.now,
        on_failure: _OnFailureCallback | None = None,
        args: tuple[Any, ...] = _NO_OP_ARGS,
        kwargs: dict[str, Any] = _NO_OP_KWARGS,
    ) -> PeriodicWorker:
        """Automatically creates a worker by analyzing object(s) methods.

        Only picks up methods that have been tagged/decorated with
        the :py:func:`.periodic` decorator (does not match against private
        or protected methods unless explicitly requested to).

        :param objects: the objects to introspect for decorated members
        :type objects: iterable
        :param exclude_hidden: exclude hidden members (ones that start with
                               an underscore)
        :type exclude_hidden: bool
        :param log: logger to use when creating a new worker (defaults
                    to the module logger if none provided), it is currently
                    only used to report callback failures (if they occur)
        :type log: logger
        :param executor_factory: factory callable that can be used to generate
                                 executor objects that will be used to
                                 run the periodic callables (if none is
                                 provided one will be created that uses
                                 the :py:class:`~futurist.SynchronousExecutor`
                                 class)
        :type executor_factory: ExecutorFactory or any callable
        :param cond_cls: callable object that can
                          produce ``threading.Condition``
                          (or compatible/equivalent) objects
        :type cond_cls: callable
        :param event_cls: callable object that can produce ``threading.Event``
                          (or compatible/equivalent) objects
        :type event_cls: callable
        :param schedule_strategy: string to select one of the built-in
                                  strategies that can return the
                                  next time a callable should run
        :type schedule_strategy: string
        :param now_func: callable that can return the current time offset
                         from some point (used in calculating elapsed times
                         and next times to run); preferably this is
                         monotonically increasing
        :type now_func: callable
        :param on_failure: callable that will be called whenever a periodic
                           function fails with an error, it will be provided
                           four positional arguments and one keyword
                           argument, the first positional argument being the
                           callable that failed, the second being the type
                           of activity under which it failed (``IMMEDIATE`` or
                           ``PERIODIC``), the third being the spacing that the
                           callable runs at and the fourth ``exc_info`` tuple
                           of the failure. The keyword argument ``traceback``
                           will also be provided that may be be a string
                           that caused the failure (this is required for
                           executors which run out of process, as those can not
                           *currently* transfer stack frames across process
                           boundaries); if no callable is provided then a
                           default failure logging function will be used
                           instead (do note that
                           any user provided callable should not raise
                           exceptions on being called)
        :type on_failure: callable
        :param args: positional arguments to be passed to all callables
        :type args: tuple
        :param kwargs: keyword arguments to be passed to all callables
        :type kwargs: dict
        """
        callables: list[
            tuple[Callable[..., Any], tuple[Any, ...], dict[str, Any]]
        ] = []
        for obj in objects:
            for name, member in inspect.getmembers(obj):
                if name.startswith("_") and exclude_hidden:
                    continue
                if callable(member):
                    missing_attrs = _check_attrs(member)
                    if not missing_attrs:
                        callables.append((member, args, kwargs))
        return cls(
            callables,
            log=log,
            executor_factory=executor_factory,
            cond_cls=cond_cls,
            event_cls=event_cls,
            schedule_strategy=schedule_strategy,
            now_func=now_func,
            on_failure=on_failure,
        )

    def __init__(
        self,
        callables: Iterable[
            tuple[
                Callable[..., Any],
                tuple[Any, ...] | None,
                dict[str, Any] | None,
            ]
        ],
        log: Logger | None = None,
        executor_factory: ExecutorFactory
        | Callable[[], futures.Executor]
        | None = None,
        cond_cls: type[threading.Condition] = threading.Condition,
        event_cls: type[threading.Event] = threading.Event,
        schedule_strategy: str = 'last_started',
        now_func: Callable[[], float] = utils.now,
        on_failure: _OnFailureCallback | None = None,
    ) -> None:
        """Creates a new worker using the given periodic callables.

        :param callables: a iterable of tuple objects previously decorated
                          with the :py:func:`.periodic` decorator, each item
                          in the iterable is expected to be in the format
                          of ``(cb, args, kwargs)`` where ``cb`` is the
                          decorated function and ``args`` and ``kwargs`` are
                          any positional and keyword arguments to send into
                          the callback when it is activated (both ``args``
                          and ``kwargs`` may be provided as none to avoid
                          using them)
        :type callables: iterable
        :param log: logger to use when creating a new worker (defaults
                    to the module logger if none provided), it is currently
                    only used to report callback failures (if they occur)
        :type log: logger
        :param executor_factory: factory callable that can be used to generate
                                 executor objects that will be used to
                                 run the periodic callables (if none is
                                 provided one will be created that uses
                                 the :py:class:`~futurist.SynchronousExecutor`
                                 class)
        :type executor_factory: ExecutorFactory or any callable
        :param cond_cls: callable object that can
                          produce ``threading.Condition``
                          (or compatible/equivalent) objects
        :type cond_cls: callable
        :param event_cls: callable object that can produce ``threading.Event``
                          (or compatible/equivalent) objects
        :type event_cls: callable
        :param schedule_strategy: string to select one of the built-in
                                  strategies that can return the
                                  next time a callable should run
        :type schedule_strategy: string
        :param now_func: callable that can return the current time offset
                         from some point (used in calculating elapsed times
                         and next times to run); preferably this is
                         monotonically increasing
        :type now_func: callable
        :param on_failure: callable that will be called whenever a periodic
                           function fails with an error, it will be provided
                           four positional arguments and one keyword
                           argument, the first positional argument being the
                           callable that failed, the second being the type
                           of activity under which it failed (``IMMEDIATE`` or
                           ``PERIODIC``), the third being the spacing that the
                           callable runs at and the fourth ``exc_info`` tuple
                           of the failure. The keyword argument ``traceback``
                           will also be provided that may be be a string
                           that caused the failure (this is required for
                           executors which run out of process, as those can not
                           *currently* transfer stack frames across process
                           boundaries); if no callable is provided then a
                           default failure logging function will be used
                           instead (do note that
                           any user provided callable should not raise
                           exceptions on being called)
        :type on_failure: callable
        """
        if on_failure is not None and not callable(on_failure):
            raise ValueError(
                f"On failure callback {on_failure!r} must be callable"
            )
        self._tombstone = event_cls()
        self._waiter = cond_cls()
        self._dead = event_cls()
        self._active = event_cls()
        self._cond_cls = cond_cls
        self._watchers = []
        self._works = []
        for cb, args, kwargs in callables:
            if not callable(cb):
                raise ValueError(f"Periodic callback {cb!r} must be callable")
            missing_attrs = _check_attrs(cb)
            if missing_attrs:
                raise ValueError(
                    f"Periodic callback {cb!r} missing required"
                    f" attributes {missing_attrs}"
                )
            if cb._is_periodic:  # type: ignore[attr-defined]
                # Ensure these aren't none and if so replace them with
                # something more appropriate...
                if args is None:
                    args = self._NO_OP_ARGS
                if kwargs is None:
                    kwargs = self._NO_OP_KWARGS.copy()
                cb_metrics = self._INITIAL_METRICS.copy()
                work = Work(utils.get_callback_name(cb), cb, args, kwargs)
                watcher = Watcher(cb_metrics, work)
                self._works.append(work)
                self._watchers.append((cb_metrics, watcher))
        try:
            strategy = self.BUILT_IN_STRATEGIES[schedule_strategy]
            self._schedule_strategy = strategy[0]
            self._initial_schedule_strategy = strategy[1]
        except KeyError:
            valid_strategies = sorted(self.BUILT_IN_STRATEGIES.keys())
            raise ValueError(
                f"Scheduling strategy '{schedule_strategy}' must be one of"
                f" {valid_strategies} selectable strategies"
            )
        self._immediates, self._schedule = _build(
            now_func, self._works, self._initial_schedule_strategy
        )
        self._log = log or LOG
        if executor_factory is None:

            def executor_factory() -> futures.Executor:
                return futurist.SynchronousExecutor()

        if on_failure is None:
            on_failure = functools.partial(_on_failure_log, self._log)
        self._on_failure = on_failure
        self._executor_factory = executor_factory
        self._now_func = now_func

    def __len__(self) -> int:
        """How many callables/periodic work units are currently active."""
        return len(self._works)

    def _run(
        self,
        executor: futures.Executor,
        runner: _Runner,
        auto_stop_when_empty: bool,
    ) -> None:
        """Main worker run loop."""
        barrier = utils.Barrier(cond_cls=self._cond_cls)
        rnd = random.SystemRandom()

        def _process_scheduled() -> None:
            # Figure out when we should run next (by selecting the
            # minimum item from the heap, where the minimum should be
            # the callable that needs to run next and has the lowest
            # next desired run time).
            with self._waiter:
                while (
                    not self._schedule
                    and not self._tombstone.is_set()
                    and not self._immediates
                ):
                    self._waiter.wait(self.MAX_LOOP_IDLE)
                if self._tombstone.is_set():
                    # We were requested to stop, so stop.
                    return
                if self._immediates:
                    # This will get processed in _process_immediates()
                    # in the next loop call.
                    return
                submitted_at = now = self._now_func()
                next_run, index = self._schedule.pop()
                when_next = next_run - now
                if when_next <= 0:
                    # Run & schedule its next execution.
                    work = self._works[index]
                    self._log.debug(
                        "Submitting periodic callback '%s'", work.name
                    )
                    try:
                        fut = executor.submit(runner.run, work)
                    except _SCHEDULE_RETRY_EXCEPTIONS as exc:
                        # Restart after a short delay
                        delay = (
                            self._RESCHEDULE_DELAY
                            + rnd.random() * self._RESCHEDULE_JITTER
                        )
                        self._log.error(
                            "Failed to submit periodic callback "
                            "'%s', retrying after %.2f sec. "
                            "Error: %s",
                            work.name,
                            delay,
                            exc,
                        )
                        self._schedule.push(self._now_func() + delay, index)
                    else:
                        barrier.incr()
                        fut.add_done_callback(
                            functools.partial(
                                _on_done, PERIODIC, work, index, submitted_at
                            )
                        )
                else:
                    # Gotta wait...
                    self._schedule.push(next_run, index)
                    when_next = min(when_next, self.MAX_LOOP_IDLE)
                    self._waiter.wait(when_next)

        def _process_immediates() -> None:
            with self._waiter:
                try:
                    index = self._immediates.popleft()
                except IndexError:
                    pass
                else:
                    work = self._works[index]
                    submitted_at = self._now_func()
                    self._log.debug(
                        "Submitting immediate callback '%s'", work.name
                    )
                    try:
                        fut = executor.submit(runner.run, work)
                    except _SCHEDULE_RETRY_EXCEPTIONS as exc:
                        self._log.error(
                            "Failed to submit immediate callback "
                            "'%s', retrying. Error: %s",
                            work.name,
                            exc,
                        )
                        # Restart as soon as possible
                        self._immediates.append(index)
                    else:
                        barrier.incr()
                        fut.add_done_callback(
                            functools.partial(
                                _on_done, IMMEDIATE, work, index, submitted_at
                            )
                        )

        def _on_done(
            kind: str,
            work: Work,
            index: int,
            submitted_at: float,
            fut: futures.Future[tuple[float, float, utils.Failure | None]],
        ) -> None:
            cb = work.callback
            started_at, finished_at, failure = fut.result()
            cb_metrics, _watcher = self._watchers[index]
            cb_metrics['runs'] = int(cb_metrics['runs']) + 1
            schedule_again = True
            if failure is not None:
                if not issubclass(failure.exc_type, NeverAgain):
                    cb_metrics['failures'] = int(cb_metrics['failures']) + 1
                    try:
                        self._on_failure(
                            cb,
                            kind,
                            cb._periodic_spacing,  # type: ignore[attr-defined]
                            failure.exc_info,
                            traceback=failure.traceback,
                        )
                    except Exception as exc:
                        self._log.error(
                            "On failure callback %r raised an"
                            " unhandled exception. Error: %s",
                            self._on_failure,
                            exc,
                        )
                else:
                    cb_metrics['successes'] = int(cb_metrics['successes']) + 1
                    schedule_again = False
                    self._log.debug(
                        "Periodic callback '%s' raised "
                        "'NeverAgain' "
                        "exception, stopping any further "
                        "execution of it.",
                        work.name,
                    )
            else:
                cb_metrics['successes'] = int(cb_metrics['successes']) + 1
            elapsed = max(0, finished_at - started_at)
            elapsed_waiting = max(0, started_at - submitted_at)
            cb_metrics['elapsed'] = float(cb_metrics['elapsed']) + elapsed
            cb_metrics['elapsed_waiting'] = (
                float(cb_metrics['elapsed_waiting']) + elapsed_waiting
            )
            with self._waiter:
                with barrier.decr_cm() as am_left:
                    if schedule_again:
                        next_run = self._schedule_strategy(
                            cb, started_at, finished_at, cb_metrics
                        )
                        self._schedule.push(next_run, index)
                    else:
                        cb_metrics['requested_stop'] = True
                        if (
                            am_left <= 0
                            and len(self._immediates) == 0
                            and len(self._schedule) == 0
                            and auto_stop_when_empty
                        ):
                            # Guess nothing left to do, goodbye...
                            self._tombstone.set()
                self._waiter.notify_all()

        try:
            while not self._tombstone.is_set():
                _process_immediates()
                _process_scheduled()
        finally:
            barrier.wait()

    def _on_finish(self) -> None:
        # TODO(harlowja): this may be to verbose for people?
        if not self._log.isEnabledFor(logging.DEBUG):
            return
        cols = list(_DEFAULT_COLS)
        for c in ['Runs in', 'Active', 'Periodicity']:
            cols.remove(c)
        self._log.debug(
            "Stopped running %s callbacks:\n%s",
            len(self._works),
            self.pformat(columns=cols)
            if prettytable
            else "statistics not available, PrettyTable missing",
        )

    def pformat(self, columns: Iterable[str] = _DEFAULT_COLS) -> str:
        if prettytable is None:
            raise ImportError(
                "PrettyTable is required to use the pformat method"
            )
        # Convert to a list to ensure we maintain the same order when used
        # further in this function (since order will matter)...
        columns_list: list[str] | tuple[str, ...]
        if not isinstance(columns, (list, tuple)):
            columns_list = list(columns)
        else:
            columns_list = columns
        if not columns_list:
            raise ValueError(
                f"At least one of {set(_DEFAULT_COLS)} columns must"
                " be provided"
            )
        for c in columns_list:
            if c not in _DEFAULT_COLS:
                raise ValueError(
                    f"Unknown column '{c}', valid column names"
                    f" are {set(_DEFAULT_COLS)}"
                )
        tbl_rows: list[dict[str, Any]] = []
        now = self._now_func()
        for index, work in enumerate(self._works):
            _cb_metrics, watcher = self._watchers[index]
            next_run = self._schedule.fetch_next_run(index)
            if watcher.requested_stop:
                active = False
                runs_in = 'n/a'
            elif next_run is None:
                active = True
                runs_in = 'n/a'
            else:
                active = False
                runs_in = f"{max(0.0, next_run - now):0.4f}s"
            cb_row: dict[str, Any] = {
                'Name': work.name,
                'Active': active,
                'Periodicity': work.callback._periodic_spacing,  # type: ignore[attr-defined]
                'Runs': watcher.runs,
                'Runs in': runs_in,
                'Failures': watcher.failures,
                'Successes': watcher.successes,
                'Stop Requested': watcher.requested_stop,
            }
            try:
                cb_row_avgs = [
                    f"{watcher.average_elapsed:0.4f}s",
                    f"{watcher.average_elapsed_waiting:0.4f}s",
                ]
            except ZeroDivisionError:
                cb_row_avgs = ['.', '.']
            cb_row['Average elapsed'] = cb_row_avgs[0]
            cb_row['Average elapsed waiting'] = cb_row_avgs[1]
            tbl_rows.append(cb_row)
        # Now form the table, but use only the columns that the caller
        # asked for (and in the order they asked for...)
        tbl = prettytable.PrettyTable(columns_list)
        for cb_row in tbl_rows:
            tbl_row: list[Any] = []
            for c in columns_list:
                tbl_row.append(cb_row[c])
            tbl.add_row(tbl_row)
        return tbl.get_string()

    def add(
        self, cb: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs
    ) -> Watcher | None:
        """Adds a new periodic callback to the current worker.

        Returns a :py:class:`.Watcher` if added successfully or the value
        ``None`` if not (or raises a ``ValueError`` if the callback is not
        correctly formed and/or decorated).

        :param cb: a callable object/method/function previously decorated
                   with the :py:func:`.periodic` decorator
        :type cb: callable
        """
        if not callable(cb):
            raise ValueError(f"Periodic callback {cb!r} must be callable")
        missing_attrs = _check_attrs(cb)
        if missing_attrs:
            raise ValueError(
                f"Periodic callback {cb!r} missing required"
                f" attributes {missing_attrs}"
            )
        if not cb._is_periodic:  # type: ignore[attr-defined]
            return None
        now = self._now_func()
        with self._waiter:
            cb_index = len(self._works)
            cb_metrics = self._INITIAL_METRICS.copy()
            work = Work(utils.get_callback_name(cb), cb, args, kwargs)
            watcher = Watcher(cb_metrics, work)
            self._works.append(work)
            self._watchers.append((cb_metrics, watcher))
            if cb._periodic_run_immediately:  # type: ignore[attr-defined]
                self._immediates.append(cb_index)
            else:
                next_run = self._initial_schedule_strategy(cb, now)
                self._schedule.push(next_run, cb_index)
            self._waiter.notify_all()
            return watcher

    def start(
        self, allow_empty: bool = False, auto_stop_when_empty: bool = False
    ) -> None:
        """Starts running (will not return until :py:meth:`.stop` is called).

        :param allow_empty: instead of running with no callbacks raise when
                            this worker has no contained callables (this can be
                            set to true and :py:meth:`.add` can be used to add
                            new callables on demand), note that when enabled
                            and no callbacks exist this will block and
                            sleep (until either stopped or callbacks are
                            added)
        :type allow_empty: bool
        :param auto_stop_when_empty: when the provided periodic functions have
                                     all exited and this is false then the
                                     thread responsible for executing those
                                     methods will just spin/idle waiting for
                                     a new periodic function to be added;
                                     switching it to true will make this
                                     idling not happen (and instead when no
                                     more periodic work exists then the
                                     calling thread will just return).
        :type auto_stop_when_empty: bool
        """
        if not self._works and not allow_empty:
            raise RuntimeError(
                "A periodic worker can not start"
                " without any callables to process"
            )
        if self._active.is_set():
            raise RuntimeError("A periodic worker can not be started twice")
        executor = self._executor_factory()
        # NOTE(harlowja): we compare with the futures process pool executor
        # since its the base type of futurist ProcessPoolExecutor and it is
        # possible for users to pass in there own custom executors, this one
        # is known to not be able to retain tracebacks...
        if isinstance(executor, futures.ProcessPoolExecutor):
            # Pickling a traceback will not work, so do not try to do it...
            #
            # Avoids 'TypeError: can't pickle traceback objects'
            runner = _Runner(self._now_func, retain_traceback=False)
        else:
            runner = _Runner(self._now_func, retain_traceback=True)
        self._dead.clear()
        self._active.set()
        try:
            self._run(executor, runner, auto_stop_when_empty)
        finally:
            if getattr(self._executor_factory, 'shutdown', True):
                executor.shutdown()
            self._dead.set()
            self._active.clear()
            self._on_finish()

    def stop(self) -> None:
        """Sets the tombstone (this stops any further executions)."""
        with self._waiter:
            self._tombstone.set()
            self._waiter.notify_all()

    def iter_watchers(self) -> Generator[Watcher, None, None]:
        """Iterator/generator over all the currently maintained watchers."""
        for _cb_metrics, watcher in self._watchers:
            yield watcher

    def reset(self) -> None:
        """Resets the workers internal state."""
        self._tombstone.clear()
        self._dead.clear()
        for cb_metrics, _watcher in self._watchers:
            for k in list(cb_metrics):
                # NOTE(harlowja): mutate the original dictionaries keys
                # so that the watcher (which references the same dictionary
                # keys) is able to see those changes.
                cb_metrics[k] = 0
        self._immediates, self._schedule = _build(
            self._now_func, self._works, self._initial_schedule_strategy
        )

    def wait(self, timeout: float | None = None) -> bool:
        """Waits for the :py:meth:`.start` method to gracefully exit.

        An optional timeout can be provided, which will cause the method to
        return within the specified timeout. If the timeout is reached, the
        returned value will be False.

        :param timeout: Maximum number of seconds that the :meth:`.wait`
                        method should block for
        :type timeout: float/int
        """
        self._dead.wait(timeout)
        return self._dead.is_set()
