"""Framework-neutral long-running Session pattern.

Important: revalidate_interval_seconds is NOT a timer. The application must
call session.check() from its own GUI timer, scheduler, or work checkpoint.
Machine and Process heartbeat pings run in SDK daemon threads only when their
options are enabled.
"""
from __future__ import annotations

import threading

from keygen_device_sdk import HeartbeatError, LicenseSDKError


def run_application(client, stop_event: threading.Event, first_license_key=None) -> None:
    try:
        with client.licensed_session(
            first_license_key,
            required_entitlements=("YOUR_FEATURE_CODE",),
            machine_heartbeat=True,
            process_seat=True,
            revalidate_interval_seconds=300,
        ) as session:
            while not stop_event.wait(15.0):
                # Usually a fast local heartbeat-health check. Every 300 seconds,
                # one of these calls also performs full HTTPS + TPM validation.
                session.check(force_validate=False)

                # Before export/burn/generation, run this in a GUI worker:
                # session.check(force_validate=True)
                # session.state.require("YOUR_FEATURE_CODE")
    except HeartbeatError as exc:
        print(f"Runtime heartbeat failed; disable protected work: {exc}")
    except LicenseSDKError as exc:
        print(f"Licensed session failed; disable protected work: {exc}")
