#!/usr/bin/env python3

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


BASE_DIR = Path(__file__).resolve().parent.parent
ENGINE = BASE_DIR / "engine" / "news_story_engine.py"

POLL_SECONDS = 30
BATCH_LIMIT = 100

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 run_incremental():

    result = subprocess.run(
        [
            sys.executable,
            str(ENGINE),
            "incremental",
            str(BATCH_LIMIT)
        ],
        cwd=str(BASE_DIR),
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True
    )

    output = (
        result.stdout or ""
    ).strip()

    # Avoid filling the log every 30 seconds when nothing happened.
    if (
        "RAW Items: 0" not in output
        or result.returncode != 0
    ):
        if output:
            print(
                output,
                flush=True
            )

    if result.returncode != 0:
        raise RuntimeError(
            f"Story engine exited with code "
            f"{result.returncode}"
        )


def main():

    log("NEWS STORY WORKER STARTED ✅")
    log(
        f"Poll interval: {POLL_SECONDS}s | "
        f"Batch limit: {BATCH_LIMIT}"
    )

    while running:

        try:
            run_incremental()

        except Exception as exc:
            log(
                f"ERROR: {type(exc).__name__}: {exc}"
            )

        # Interruptible sleep.
        for _ in range(POLL_SECONDS):

            if not running:
                break

            time.sleep(1)

    log("NEWS STORY WORKER STOPPED")


if __name__ == "__main__":
    main()
