#!/usr/bin/env python3

import signal
import sys
import time
from datetime import datetime
from pathlib import Path


BASE_DIR = Path(__file__).resolve().parent.parent
ENGINE_DIR = BASE_DIR / "engine"

sys.path.insert(
    0,
    str(ENGINE_DIR)
)

import news_publisher


POLL_SECONDS = 2
IDLE_SECONDS = 2
ERROR_SECONDS = 5
MAX_PER_CYCLE = 20

running = True


def log(message):
    print(
        f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] "
        f"{message}",
        flush=True
    )


def stop_handler(signum, frame):
    global running

    running = False

    log(
        "STOP REQUESTED"
    )


signal.signal(
    signal.SIGTERM,
    stop_handler
)

signal.signal(
    signal.SIGINT,
    stop_handler
)


def main():

    log(
        "NEWS PUBLISHER WORKER STARTED ✅"
    )

    log(
        f"Poll={POLL_SECONDS}s | "
        f"Max per cycle={MAX_PER_CYCLE}"
    )

    while running:

        published_this_cycle = 0

        try:

            for _ in range(
                MAX_PER_CYCLE
            ):

                if not running:
                    break

                result = (
                    news_publisher.publish_one()
                )

                # publish_one:
                # 0 = published
                # 2 = no ready job
                # 1 = error

                if result == 0:

                    published_this_cycle += 1

                    # Tiny gap between Telegram sends.
                    time.sleep(1)

                    continue

                if result == 2:
                    break

                if result == 1:

                    log(
                        "PUBLISH ERROR — "
                        "waiting before retry"
                    )

                    time.sleep(
                        ERROR_SECONDS
                    )

                    break

            if (
                published_this_cycle
                > 0
            ):
                log(
                    "CYCLE COMPLETE | "
                    f"published="
                    f"{published_this_cycle}"
                )

        except Exception as exc:

            log(
                "WORKER ERROR: "
                f"{type(exc).__name__}: "
                f"{exc}"
            )

            time.sleep(
                ERROR_SECONDS
            )

        # Interruptible idle wait.
        for _ in range(
            IDLE_SECONDS
        ):

            if not running:
                break

            time.sleep(1)

    log(
        "NEWS PUBLISHER WORKER STOPPED"
    )


if __name__ == "__main__":
    main()
