"""Worker configuration (env and defaults)."""

from __future__ import annotations

import os
import platform
import uuid
from dataclasses import dataclass, field


def _default_worker_id() -> str:
    return f"{platform.node() or 'worker'}-{os.getpid()}-{uuid.uuid4().hex[:8]}"


@dataclass
class WorkerConfig:
    """Configuration for the PyCharter worker process."""

    db_url: str | None = None
    poll_interval_ms: int = 500
    concurrency: int = 5
    drain_timeout_s: int = 30
    max_attempts: int = 5
    worker_id: str = field(default_factory=_default_worker_id)
    claim_lease_timeout_s: int = 300
    retry_backoff_base_ms: int = 1000
    retry_backoff_max_ms: int = 300000

    def __post_init__(self) -> None:
        if self.db_url is None:
            self.db_url = os.environ.get("PYCHARTER_WORKER_DB_URL")
            if not self.db_url:
                from pycharter.config import get_database_url

                self.db_url = get_database_url()

    def resolve_db_url(self) -> str:
        if self.db_url:
            return self.db_url
        raise ValueError(
            "No database URL. Set PYCHARTER_DATABASE_URL, PYCHARTER_WORKER_DB_URL, "
            "or set PYCHARTER_DATABASE_URL (env or pycharter.cfg [database])."
        )
