"""CLI commands for worker component."""

from __future__ import annotations

import asyncio
import logging
import sys

logger = logging.getLogger(__name__)


def cmd_worker_start(
    concurrency: int | None = None,
    poll_interval: int | None = None,
) -> int:
    """Start the validation worker."""
    from pycharter.worker.config import WorkerConfig
    from pycharter.worker.runner import Worker

    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    )

    config = WorkerConfig()
    if concurrency is not None:
        config.concurrency = concurrency
    if poll_interval is not None:
        config.poll_interval_ms = poll_interval

    try:
        config.resolve_db_url()
    except ValueError as e:
        print(f"Error: {e}", file=sys.stderr)
        return 1

    worker = Worker(config=config)

    async def _run() -> None:
        await worker.start()
        await worker.run()

    try:
        asyncio.run(_run())
    except KeyboardInterrupt:
        logger.info("Worker stopped by user")
    return 0
