"""
Magento sync queue worker.

Usage:
  python magento_worker.py           # run continuously (default: poll every 60s when idle)
  python magento_worker.py --once    # process one item and exit (for external schedulers)
  python magento_worker.py --poll 30 # run continuously, poll every 30s when idle
"""
import argparse
import logging
import time

from dotenv import load_dotenv

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

DEFAULT_POLL_SECONDS = 60


def main() -> None:
    load_dotenv()
    parser = argparse.ArgumentParser(description="Magento sync queue worker")
    parser.add_argument("--once", action="store_true", help="Process one item and exit")
    parser.add_argument("--poll", type=int, default=DEFAULT_POLL_SECONDS,
                        help=f"Seconds to sleep when queue is empty (default: {DEFAULT_POLL_SECONDS})")
    args = parser.parse_args()

    from app.jobs.magento_sync_worker import run_one

    # MAGENTO_SYNC_WORKER_ENABLED only gates the embedded daemon thread in main.py
    # (uvicorn). This standalone CLI is meant for systemd/supervisor — always run
    # when invoked directly, same as channel_job_worker.
    if args.once:
        run_one()
        return

    logger.info("magento-worker: starting continuous loop (idle poll=%ss)", args.poll)
    while True:
        try:
            had_work = run_one()
        except Exception as exc:
            logger.exception("magento-worker: unexpected error: %s", exc)
            had_work = False

        if not had_work:
            logger.debug("magento-worker: queue empty, sleeping %ss", args.poll)
            time.sleep(args.poll)
        # if had_work: loop immediately — drain the queue without delay


if __name__ == "__main__":
    main()
