"""Background watchdog that periodically checks license validity.

If the lease expires or is revoked, the watchdog terminates the application.
"""

import os
import threading
import logging

logger = logging.getLogger("cgt_license")

WATCHDOG_INTERVAL = 120  # seconds


def start_watchdog(guard, interval: int = WATCHDOG_INTERVAL):
    """Start background watchdog that checks license validity.

    Every `interval` seconds, calls guard.ping().
    If ping returns False (lease expired, secret revoked), terminates the app.
    """
    stop_event = threading.Event()

    def _run():
        while not stop_event.is_set():
            stop_event.wait(interval)
            if stop_event.is_set():
                break
            if not guard.ping():
                logger.error(
                    "License check failed — lease expired or revoked. "
                    "Shutting down."
                )
                os._exit(1)

    thread = threading.Thread(
        target=_run, name="cgt-license-watchdog", daemon=True
    )
    thread.start()
    return stop_event  # Can be used to stop watchdog in tests
