from __future__ import annotations

import logging
import math
import os
import random
import re
import json
import signal
import sqlite3
import threading
import time
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from pathlib import Path
from typing import Any, Callable, Iterator, Literal
from urllib.parse import urlparse

import requests


__version__ = "1.4.2"

TargetType = Literal["global", "community"]
HandlerErrorAction = Literal["retry", "skip", "stop"]
HandlerResult = Any
MessageCallback = Callable[["CommandContext"], HandlerResult]
ErrorCallback = Callable[["CommandContext", Exception], HandlerErrorAction | str | None]
SDK_USER_AGENT = f"HarborBot.py/{__version__}"
API_VERSION = "1"
DELIVERY_GUARANTEE = "at_least_once"
BOT_API_PREFIX = "/api/bot/v1"
OFFICIAL_HARBOR_HOST_SUFFIX = "harborproject.ru"
BOT_TOKEN_PREFIXES = ("hbr_bot_live_", "hbr_bot_test_")
_TOKEN_PATTERN = re.compile(r"hbr_bot_(?:live|test)_[A-Za-z0-9._~+-]+")

__all__ = [
    "API_VERSION",
    "BOT_API_PREFIX",
    "BOT_TOKEN_PREFIXES",
    "BotRuntimeInvite",
    "BotRuntimeTarget",
    "BotTokenAuth",
    "CommandContext",
    "CursorStore",
    "DELIVERY_GUARANTEE",
    "FileCursorStore",
    "HarborBot",
    "HarborBotAmbiguousTargetError",
    "HarborBotApiError",
    "HarborBotConfigError",
    "HarborBotConflictError",
    "HarborBotError",
    "HarborBotForbiddenError",
    "HarborBotHandlerError",
    "HarborBotNotFoundError",
    "HarborBotRateLimitError",
    "HarborBotTokenError",
    "HarborBotUnauthorizedError",
    "HarborChatApi",
    "HarborCommunityApi",
    "HarborErrorHandler",
    "HarborMessage",
    "HarborMessageBatch",
    "HarborRouter",
    "HarborRuntimeConfig",
    "HandlerErrorAction",
    "HandlerResult",
    "MemoryCursorStore",
    "MessageCallback",
    "OFFICIAL_HARBOR_HOST_SUFFIX",
    "PollingBot",
    "SDK_USER_AGENT",
    "SQLiteCursorStore",
    "TargetType",
    "__version__",
    "mask_identifier",
    "mask_token",
    "safe_log_extra",
    "sanitize_secret_text",
]


def mask_token(token: str | None, *, visible: int = 4) -> str:
    """Return a log-safe token representation."""

    value = (token or "").strip()
    if not value:
        return "***"
    tail = value[-visible:] if len(value) > visible else value
    return f"***{tail}"


def mask_identifier(value: str | None, *, visible: int = 6) -> str:
    """Return a log-safe identifier representation."""

    raw = (value or "").strip()
    if not raw:
        return ""
    if len(raw) <= visible:
        return f"***{raw}"
    return f"***{raw[-visible:]}"


def safe_log_extra(event: str, **fields: Any) -> dict[str, Any]:
    """Build structured logging fields without exposing tokens or private payloads."""

    extra: dict[str, Any] = {
        "harbor_event": event,
        "sdk_version": __version__,
        "api_version": API_VERSION,
        "delivery_guarantee": DELIVERY_GUARANTEE,
    }
    for key, value in fields.items():
        if value is None:
            continue
        if key == "target_id":
            extra["target_id_masked"] = mask_identifier(str(value))
            continue
        if key == "idempotency_key":
            extra["idempotency_key_masked"] = mask_identifier(str(value))
            continue
        if key in {"message_id", "cursor"}:
            extra[key] = mask_identifier(str(value))
            continue
        if isinstance(value, str):
            extra[key] = sanitize_secret_text(value)
            continue
        extra[key] = value
    return extra


def _duration_ms(started_at: float) -> int:
    return max(0, int((time.monotonic() - started_at) * 1000))


def sanitize_secret_text(text: str | None) -> str:
    """Mask Harbor bot tokens in diagnostic text."""

    value = text or ""
    return _TOKEN_PATTERN.sub(lambda match: mask_token(match.group(0)), value)


def _received(value: Any) -> str:
    return f'"{sanitize_secret_text(str(value))}"'


def _is_stopped(stop_event: threading.Event | None) -> bool:
    return bool(stop_event is not None and stop_event.is_set())


def _sleep_or_stop(seconds: float, stop_event: threading.Event | None = None) -> bool:
    delay = max(0.0, float(seconds))
    if stop_event is not None:
        return stop_event.wait(delay)
    time.sleep(delay)
    return False


def _normalize_handler_action(action: HandlerErrorAction | str | None) -> HandlerErrorAction:
    value = str(action or "retry").strip().lower()
    if value in {"retry", "skip", "stop"}:
        return value  # type: ignore[return-value]
    raise HarborBotConfigError(f"handler error policy must be retry, skip, or stop. Received: {_received(action)}")


def _is_official_harbor_host(hostname: str | None) -> bool:
    host = (hostname or "").strip().lower().rstrip(".")
    return host == OFFICIAL_HARBOR_HOST_SUFFIX or host.endswith(f".{OFFICIAL_HARBOR_HOST_SUFFIX}")


def _coerce_positive_float(name: str, value: Any) -> float:
    try:
        parsed = float(value)
    except (TypeError, ValueError) as exc:
        raise HarborBotConfigError(f"{name} must be a positive number. Received: {_received(value)}") from exc

    if not math.isfinite(parsed) or parsed <= 0:
        raise HarborBotConfigError(f"{name} must be a positive number. Received: {_received(value)}")
    return parsed


def _coerce_int_range(name: str, value: Any, *, minimum: int, maximum: int) -> int:
    try:
        parsed = int(value)
    except (TypeError, ValueError) as exc:
        raise HarborBotConfigError(f"{name} must be an integer from {minimum} to {maximum}. Received: {_received(value)}") from exc

    if parsed < minimum or parsed > maximum:
        raise HarborBotConfigError(f"{name} must be from {minimum} to {maximum}. Received: {_received(value)}")
    return parsed


def _read_positive_float_env(name: str, default: str) -> float:
    return _coerce_positive_float(name, os.environ.get(name, default))


def _read_int_range_env(name: str, default: str, *, minimum: int, maximum: int) -> int:
    return _coerce_int_range(name, os.environ.get(name, default), minimum=minimum, maximum=maximum)


def _normalize_base_url(base_url: str) -> str:
    value = (base_url or "").strip().rstrip("/")
    if not value:
        raise HarborBotConfigError("base_url must not be empty.")

    parsed = urlparse(value)
    if parsed.scheme not in {"http", "https"} or not parsed.netloc:
        raise HarborBotConfigError(f"base_url must be an absolute HTTP(S) URL. Received: {_received(value)}")
    if parsed.username or parsed.password:
        raise HarborBotConfigError("base_url must not contain username or password.")
    if parsed.query or parsed.fragment:
        raise HarborBotConfigError("base_url must not contain query string or fragment.")
    return value


def _validate_base_url_for_token(
    base_url: str,
    auth: "BotTokenAuth",
    *,
    allow_unsafe_base_url: bool,
) -> str:
    value = _normalize_base_url(base_url)
    parsed = urlparse(value)
    host = parsed.hostname

    if auth.is_live_token:
        if parsed.scheme != "https" or not _is_official_harbor_host(host):
            raise HarborBotConfigError(
                "Production bot tokens can only be used with official HTTPS Harbor domains."
            )
        return value

    if parsed.scheme == "https" and _is_official_harbor_host(host):
        return value

    if not allow_unsafe_base_url:
        raise HarborBotConfigError(
            "Unsafe base_url is allowed only for test bot tokens with allow_unsafe_base_url=True."
        )
    return value


class HarborBotError(RuntimeError):
    """Base exception for HarborBot.py."""


class HarborBotConfigError(HarborBotError, ValueError):
    """Raised when local bot configuration is invalid."""


class HarborBotTokenError(HarborBotConfigError):
    """Raised when a token is missing or has an unsupported format."""


class HarborBotAmbiguousTargetError(HarborBotConfigError):
    """Raised when automatic target selection is ambiguous."""


class HarborBotApiError(HarborBotError):
    """Raised when Harbor API returns a non-success HTTP status."""

    def __init__(
        self,
        status_code: int,
        message: str,
        *,
        code: str | None = None,
        response_text: str = "",
    ) -> None:
        safe_message = sanitize_secret_text(message)
        safe_response_text = sanitize_secret_text(response_text)
        details = f"HTTP {status_code}: {safe_message}"
        if code:
            details = f"{details} ({code})"
        super().__init__(details)
        self.status_code = status_code
        self.code = code
        self.response_text = safe_response_text


class HarborBotUnauthorizedError(HarborBotApiError):
    """Raised when a bot token is missing, invalid, revoked, or expired."""


class HarborBotForbiddenError(HarborBotApiError):
    """Raised when the bot has no required scope or grant."""


class HarborBotNotFoundError(HarborBotApiError):
    """Raised when a target chat or resource does not exist."""


class HarborBotConflictError(HarborBotApiError):
    """Raised when the requested action conflicts with current state."""


class HarborBotRateLimitError(HarborBotApiError):
    """Raised when runtime rate limit is reached."""

    def __init__(self, retry_after_seconds: int | None, response_text: str = "") -> None:
        message = "runtime rate limit reached"
        if retry_after_seconds is not None:
            message = f"{message}; retry after {retry_after_seconds}s"
        super().__init__(
            429,
            message,
            code="bot_rate_limited",
            response_text=response_text,
        )
        self.retry_after_seconds = retry_after_seconds


class HarborBotHandlerError(HarborBotError):
    """Raised internally when user handler fails and should be retried."""

    def __init__(self, context: "CommandContext", original_error: Exception) -> None:
        message_id = context.message.id
        super().__init__(
            "handler error: "
            f"target_type={context.target_type} "
            f"target_id={mask_identifier(context.target_id)} "
            f"message_id={mask_identifier(message_id)} "
            f"error={original_error.__class__.__name__}"
        )
        self.context = context
        self.original_error = original_error


class CursorStore:
    """Checkpoint storage for the last successfully handled message ID.

    The stored value is passed back to Bot API as afterMessageId. It is not
    assumed to be an opaque server cursor.
    """

    def load(self, target_type: TargetType, target_id: str) -> str | None:
        raise NotImplementedError

    def save(self, target_type: TargetType, target_id: str, cursor: str) -> None:
        raise NotImplementedError


class MemoryCursorStore(CursorStore):
    """In-process checkpoint storage shared across polling restarts."""

    def __init__(self) -> None:
        self._values: dict[str, str] = {}
        self._lock = threading.RLock()

    @staticmethod
    def key(target_type: TargetType, target_id: str) -> str:
        return f"{target_type}:{target_id}"

    def load(self, target_type: TargetType, target_id: str) -> str | None:
        with self._lock:
            return self._values.get(self.key(target_type, target_id))

    def save(self, target_type: TargetType, target_id: str, cursor: str) -> None:
        value = (cursor or "").strip()
        if not value:
            return
        with self._lock:
            self._values[self.key(target_type, target_id)] = value


class FileCursorStore(CursorStore):
    """JSON-file checkpoint storage for simple bots and local services."""

    def __init__(self, path: str | os.PathLike[str]) -> None:
        self.path = Path(path)
        self._lock = threading.RLock()

    @staticmethod
    def key(target_type: TargetType, target_id: str) -> str:
        return f"{target_type}:{target_id}"

    def load(self, target_type: TargetType, target_id: str) -> str | None:
        with self._lock:
            values = self._read()
            value = values.get(self.key(target_type, target_id))
            return str(value) if value else None

    def save(self, target_type: TargetType, target_id: str, cursor: str) -> None:
        value = (cursor or "").strip()
        if not value:
            return
        with self._lock:
            values = self._read()
            values[self.key(target_type, target_id)] = value
            self.path.parent.mkdir(parents=True, exist_ok=True)
            tmp_path = self.path.with_suffix(f"{self.path.suffix}.tmp")
            tmp_path.write_text(
                json.dumps(values, ensure_ascii=False, indent=2, sort_keys=True),
                encoding="utf-8",
            )
            os.replace(tmp_path, self.path)

    def _read(self) -> dict[str, str]:
        if not self.path.exists():
            return {}
        try:
            payload = json.loads(self.path.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError) as exc:
            raise HarborBotConfigError(f"Cursor store file is not readable JSON: {self.path}") from exc
        if not isinstance(payload, dict):
            raise HarborBotConfigError(f"Cursor store file must contain a JSON object: {self.path}")
        return {str(key): str(value) for key, value in payload.items() if value}


class SQLiteCursorStore(CursorStore):
    """SQLite checkpoint storage using only Python standard library modules."""

    def __init__(self, path: str | os.PathLike[str]) -> None:
        self.path = Path(path)
        self._lock = threading.RLock()
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self._initialize()

    def load(self, target_type: TargetType, target_id: str) -> str | None:
        with self._lock, sqlite3.connect(self.path) as connection:
            row = connection.execute(
                """
                SELECT cursor
                FROM harborbot_cursors
                WHERE target_type = ? AND target_id = ?
                """,
                (target_type, target_id),
            ).fetchone()
        return str(row[0]) if row and row[0] else None

    def save(self, target_type: TargetType, target_id: str, cursor: str) -> None:
        value = (cursor or "").strip()
        if not value:
            return
        with self._lock, sqlite3.connect(self.path) as connection:
            connection.execute(
                """
                INSERT INTO harborbot_cursors(target_type, target_id, cursor, updated_at_utc)
                VALUES (?, ?, ?, ?)
                ON CONFLICT(target_type, target_id)
                DO UPDATE SET cursor = excluded.cursor, updated_at_utc = excluded.updated_at_utc
                """,
                (
                    target_type,
                    target_id,
                    value,
                    datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
                ),
            )

    def _initialize(self) -> None:
        with sqlite3.connect(self.path) as connection:
            connection.execute(
                """
                CREATE TABLE IF NOT EXISTS harborbot_cursors(
                    target_type TEXT NOT NULL,
                    target_id TEXT NOT NULL,
                    cursor TEXT NOT NULL,
                    updated_at_utc TEXT NOT NULL,
                    PRIMARY KEY(target_type, target_id)
                )
                """
            )


@dataclass(frozen=True)
class BotTokenAuth:
    """Token-only auth helper for Harbor Bot Runtime.

    This class intentionally accepts only Harbor bot tokens. User Bearer/JWT
    tokens are rejected before a request is sent.
    """

    token: str = field(repr=False)

    def __post_init__(self) -> None:
        object.__setattr__(self, "token", self.normalize(self.token))

    def __repr__(self) -> str:
        return f'{self.__class__.__name__}(token="{self.masked_token}")'

    @classmethod
    def from_env(cls, env_name: str = "HARBOR_BOT_TOKEN") -> "BotTokenAuth":
        token = os.environ.get(env_name)
        if not token:
            raise HarborBotTokenError(f"{env_name} is required")
        return cls(token)

    @property
    def authorization_header(self) -> str:
        return f"Bot {self.token}"

    @property
    def masked_token(self) -> str:
        return mask_token(self.token)

    @property
    def is_live_token(self) -> bool:
        return self.token.startswith("hbr_bot_live_")

    @property
    def is_test_token(self) -> bool:
        return self.token.startswith("hbr_bot_test_")

    @property
    def headers(self) -> dict[str, str]:
        return {
            "Authorization": self.authorization_header,
            "Accept": "application/json",
        }

    @staticmethod
    def normalize(token: str) -> str:
        value = (token or "").strip()
        if value.lower().startswith("bot "):
            value = value[4:].strip()
        if value.lower().startswith("bearer "):
            raise HarborBotTokenError("User Bearer/JWT tokens are not supported. Use a Harbor bot token.")
        if value.count(".") == 2:
            raise HarborBotTokenError("JWT tokens are not supported. Use a Harbor bot token.")
        if not value.startswith(BOT_TOKEN_PREFIXES):
            raise HarborBotTokenError("Expected a Harbor bot token starting with 'hbr_bot_live_' or 'hbr_bot_test_'.")
        return value


@dataclass(frozen=True)
class HarborRuntimeConfig:
    """Runtime settings shared by examples and long-running bots."""

    token: str = field(repr=False)
    target_type: TargetType = "community"
    target_id: str = ""
    base_url: str = "https://harborproject.ru"
    poll_interval_seconds: float = 2.0
    take: int = 50
    timeout: float = 30

    def __post_init__(self) -> None:
        token = BotTokenAuth.normalize(self.token)
        target_type = str(self.target_type).strip().lower()
        if target_type not in {"global", "community"}:
            raise HarborBotConfigError(f"target_type must be 'global' or 'community'. Received: {_received(target_type)}")

        object.__setattr__(self, "token", token)
        object.__setattr__(self, "target_type", target_type)
        object.__setattr__(self, "target_id", str(self.target_id or "").strip())
        object.__setattr__(self, "base_url", _normalize_base_url(self.base_url))
        object.__setattr__(self, "poll_interval_seconds", _coerce_positive_float("poll_interval_seconds", self.poll_interval_seconds))
        object.__setattr__(self, "take", _coerce_int_range("poll_take", self.take, minimum=1, maximum=100))
        object.__setattr__(self, "timeout", _coerce_positive_float("timeout", self.timeout))

    def __repr__(self) -> str:
        return (
            f'{self.__class__.__name__}(token="{mask_token(self.token)}", '
            f"target_type={self.target_type!r}, target_id={self.target_id!r}, "
            f"base_url={self.base_url!r}, poll_interval_seconds={self.poll_interval_seconds!r}, "
            f"take={self.take!r}, timeout={self.timeout!r})"
        )

    @classmethod
    def from_env(cls) -> "HarborRuntimeConfig":
        target_type = os.environ.get("HARBOR_CHAT_TYPE", "community").strip().lower()
        if target_type not in {"global", "community"}:
            raise HarborBotConfigError("HARBOR_CHAT_TYPE must be 'global' or 'community'")

        token = os.environ.get("HARBOR_BOT_TOKEN")
        if not token:
            raise HarborBotTokenError("HARBOR_BOT_TOKEN is required")

        return cls(
            token=token,
            target_type=target_type,  # type: ignore[arg-type]
            target_id=os.environ.get("HARBOR_CHAT_ID", "").strip(),
            base_url=os.environ.get("HARBOR_BASE_URL", "https://harborproject.ru").rstrip("/"),
            poll_interval_seconds=_read_positive_float_env("HARBOR_POLL_INTERVAL", "2"),
            take=_read_int_range_env("HARBOR_POLL_TAKE", "50", minimum=1, maximum=100),
            timeout=_read_positive_float_env("HARBOR_TIMEOUT", "30"),
        )

    def require_target(self) -> "HarborRuntimeConfig":
        if not self.target_id:
            raise HarborBotConfigError("HARBOR_CHAT_ID is required")
        return self


@dataclass(frozen=True)
class BotRuntimeTarget:
    """Chat or room available to the bot runtime token."""

    runtime_type: TargetType
    target_type: str
    target_id: str
    community_id: str | None
    name: str
    scopes: tuple[str, ...]
    is_private: bool
    raw: dict[str, Any]

    @classmethod
    def from_payload(cls, payload: dict[str, Any]) -> "BotRuntimeTarget":
        runtime_type = str(payload.get("runtimeType") or "").strip().lower()
        if runtime_type not in {"global", "community"}:
            raise HarborBotConfigError("runtime target type must be 'global' or 'community'")

        target_id = str(payload.get("targetId") or "").strip()
        if not target_id:
            raise HarborBotConfigError("runtime target id is empty")

        raw_scopes = payload.get("scopes")
        scopes = tuple(str(scope).strip() for scope in raw_scopes if str(scope).strip()) \
            if isinstance(raw_scopes, list) else ()

        community_id = payload.get("communityId")
        return cls(
            runtime_type=runtime_type,  # type: ignore[arg-type]
            target_type=str(payload.get("targetType") or ""),
            target_id=target_id,
            community_id=str(community_id) if community_id else None,
            name=str(payload.get("name") or ""),
            scopes=scopes,
            is_private=bool(payload.get("isPrivate")),
            raw=payload,
        )

    def has_scope(self, scope: str) -> bool:
        return scope.lower() in {value.lower() for value in self.scopes}


@dataclass(frozen=True)
class BotRuntimeInvite:
    """Pending private community-room invite available to the bot runtime token."""

    runtime_type: TargetType
    target_type: str
    target_id: str
    community_id: str | None
    name: str
    scopes: tuple[str, ...]
    invited_by_user_id: str | None
    invited_at_utc: str | None
    is_private: bool
    raw: dict[str, Any]

    @classmethod
    def from_payload(cls, payload: dict[str, Any]) -> "BotRuntimeInvite":
        runtime_type = str(payload.get("runtimeType") or "").strip().lower()
        if runtime_type not in {"global", "community"}:
            raise HarborBotConfigError("runtime invite type must be 'global' or 'community'")

        target_id = str(payload.get("targetId") or "").strip()
        if not target_id:
            raise HarborBotConfigError("runtime invite target id is empty")

        raw_scopes = payload.get("scopes")
        scopes = tuple(str(scope).strip() for scope in raw_scopes if str(scope).strip()) \
            if isinstance(raw_scopes, list) else ()

        community_id = payload.get("communityId")
        invited_by_user_id = payload.get("invitedByUserId")
        invited_at_utc = payload.get("invitedAtUtc")
        return cls(
            runtime_type=runtime_type,  # type: ignore[arg-type]
            target_type=str(payload.get("targetType") or ""),
            target_id=target_id,
            community_id=str(community_id) if community_id else None,
            name=str(payload.get("name") or ""),
            scopes=scopes,
            invited_by_user_id=str(invited_by_user_id) if invited_by_user_id else None,
            invited_at_utc=str(invited_at_utc) if invited_at_utc else None,
            is_private=bool(payload.get("isPrivate")),
            raw=payload,
        )

    def has_scope(self, scope: str) -> bool:
        return scope.lower() in {value.lower() for value in self.scopes}


@dataclass(frozen=True)
class HarborMessage:
    """Small wrapper over raw message JSON returned by Harbor."""

    raw: dict[str, Any]
    target_type: TargetType | None = None
    target_id: str | None = None

    @property
    def id(self) -> str:
        return str(self.raw.get("id") or "")

    @property
    def text(self) -> str:
        return str(self.raw.get("text") or "")

    @property
    def created_at_utc(self) -> str:
        return str(self.raw.get("createdAtUtc") or "")

    @property
    def author(self) -> dict[str, Any]:
        value = self.raw.get("author")
        return value if isinstance(value, dict) else {}

    @property
    def author_id(self) -> str:
        return str(self.author.get("id") or "")

    @property
    def author_user_name(self) -> str:
        return str(self.author.get("userName") or "")

    @property
    def author_name(self) -> str:
        return str(self.author.get("displayName") or self.author.get("userName") or "")

    @property
    def author_is_bot(self) -> bool:
        return bool(self.author.get("isBot"))

    @property
    def message_type(self) -> str:
        return str(self.raw.get("messageType") or "")

    @property
    def reply_to_message_id(self) -> str | None:
        value = self.raw.get("replyToMessageId")
        return str(value) if value else None

    @property
    def media(self) -> dict[str, Any] | None:
        value = self.raw.get("media")
        return value if isinstance(value, dict) else None

    def is_command(self, prefix: str = "/") -> bool:
        return self.text.strip().startswith(prefix)

    def command_name(self, prefix: str = "/") -> str:
        text = self.text.strip()
        if not text.startswith(prefix):
            return ""
        return text[len(prefix):].split(maxsplit=1)[0].lower()

    def command_args(self, prefix: str = "/") -> str:
        text = self.text.strip()
        if not text.startswith(prefix):
            return ""
        parts = text[len(prefix):].split(maxsplit=1)
        return parts[1] if len(parts) == 2 else ""

    def contains_any(self, words: list[str] | tuple[str, ...], *, case_sensitive: bool = False) -> bool:
        text = self.text if case_sensitive else self.text.lower()
        for word in words:
            needle = word if case_sensitive else word.lower()
            if needle and needle in text:
                return True
        return False


@dataclass(frozen=True)
class HarborMessageBatch:
    """Message page returned by Bot API v1 with server checkpoint metadata."""

    messages: tuple[HarborMessage, ...]
    cursor: str | None = None
    continuation_token: str | None = None
    has_more: bool = False


class HarborErrorHandler:
    """Small helper for consistent runtime error handling."""

    def __init__(
        self,
        *,
        logger: logging.Logger | None = None,
        max_rate_limit_sleep: int | None = None,
    ) -> None:
        self.logger = logger or logging.getLogger("HarborBot")
        self.max_rate_limit_sleep = max_rate_limit_sleep

    def sleep_for_rate_limit(self, error: HarborBotRateLimitError) -> None:
        retry_after = error.retry_after_seconds
        delay = retry_after if retry_after is not None else 5
        if self.max_rate_limit_sleep is not None:
            delay = min(self.max_rate_limit_sleep, delay)
        self.logger.warning(
            "Rate limited; sleeping for %ss",
            delay,
            extra=safe_log_extra("rate_limited", retry_after=delay, status_code=429),
        )
        time.sleep(delay)

    def log_api_error(self, error: HarborBotApiError) -> None:
        self.logger.warning(
            "Harbor API error: status=%s code=%s text=%s",
            error.status_code,
            error.code,
            error.response_text[:500],
            extra=safe_log_extra(
                "api_error",
                status_code=error.status_code,
                error_code=error.code,
            ),
        )

    def handle_callback_error(self, context: "CommandContext", error: Exception) -> HandlerErrorAction:
        self.logger.exception(
            "Handler error: target_type=%s target_id=%s message_id=%s error=%s",
            context.target_type,
            mask_identifier(context.target_id),
            mask_identifier(context.message.id),
            error.__class__.__name__,
            extra=safe_log_extra(
                "handler_error",
                target_type=context.target_type,
                target_id=context.target_id,
                message_id=context.message.id,
                error_type=error.__class__.__name__,
            ),
        )
        return "retry"

    def should_continue(self, error: Exception) -> bool:
        if isinstance(error, HarborBotRateLimitError):
            self.sleep_for_rate_limit(error)
            return True
        if isinstance(error, HarborBotHandlerError):
            return True
        if isinstance(error, HarborBotApiError):
            self.log_api_error(error)
            return error.status_code >= 500
        self.logger.exception(
            "Unhandled bot error",
            extra=safe_log_extra("unhandled_error", error_type=error.__class__.__name__),
        )
        return True


class HarborChatApi:
    """Runtime API for global chats and target-agnostic chat helpers."""

    def __init__(self, client: "HarborBot") -> None:
        self.client = client

    def get_global_messages(
        self,
        chat_id: str,
        *,
        take: int = 50,
        before_utc: str | datetime | None = None,
    ) -> list[HarborMessage]:
        return list(self.get_global_messages_page(chat_id, take=take, before_utc=before_utc).messages)

    def get_global_messages_page(
        self,
        chat_id: str,
        *,
        take: int = 50,
        before_utc: str | datetime | None = None,
        after_message_id: str | None = None,
        cursor: str | None = None,
    ) -> HarborMessageBatch:
        payload = self.client.request(
            "GET",
            f"{BOT_API_PREFIX}/global-chats/{chat_id}/messages",
            params=self.client.message_params(
                take,
                before_utc,
                after_message_id=after_message_id,
                cursor=cursor,
            ),
        )
        return self.client.message_batch_from_payload(payload, target_type="global", target_id=chat_id)

    def send_global_message(
        self,
        chat_id: str,
        text: str,
        *,
        media_id: str | None = None,
        reply_to_message_id: str | None = None,
        idempotency_key: str | None = None,
    ) -> dict[str, Any]:
        return self.client.request(
            "POST",
            f"{BOT_API_PREFIX}/global-chats/{chat_id}/messages",
            json_body={
                "text": text,
                "mediaId": media_id,
                "replyToMessageId": reply_to_message_id,
            },
            idempotency_key=idempotency_key,
        )

    def get_messages(
        self,
        target_type: TargetType,
        target_id: str,
        *,
        take: int = 50,
        before_utc: str | datetime | None = None,
    ) -> list[HarborMessage]:
        return list(self.get_messages_page(target_type, target_id, take=take, before_utc=before_utc).messages)

    def get_messages_page(
        self,
        target_type: TargetType,
        target_id: str,
        *,
        take: int = 50,
        before_utc: str | datetime | None = None,
        after_message_id: str | None = None,
        cursor: str | None = None,
    ) -> HarborMessageBatch:
        if target_type == "global":
            return self.get_global_messages_page(
                target_id,
                take=take,
                before_utc=before_utc,
                after_message_id=after_message_id,
                cursor=cursor,
            )
        if target_type == "community":
            return self.client.community.get_room_messages_page(
                target_id,
                take=take,
                before_utc=before_utc,
                after_message_id=after_message_id,
                cursor=cursor,
            )
        raise HarborBotConfigError("target_type must be 'global' or 'community'")

    def send_message(
        self,
        target_type: TargetType,
        target_id: str,
        text: str,
        *,
        media_id: str | None = None,
        reply_to_message_id: str | None = None,
        idempotency_key: str | None = None,
    ) -> dict[str, Any]:
        if target_type == "global":
            return self.send_global_message(
                target_id,
                text,
                media_id=media_id,
                reply_to_message_id=reply_to_message_id,
                idempotency_key=idempotency_key,
            )
        if target_type == "community":
            return self.client.community.send_room_message(
                target_id,
                text,
                media_id=media_id,
                reply_to_message_id=reply_to_message_id,
                idempotency_key=idempotency_key,
            )
        raise HarborBotConfigError("target_type must be 'global' or 'community'")


class HarborCommunityApi:
    """Runtime API for community chat rooms."""

    def __init__(self, client: "HarborBot") -> None:
        self.client = client

    def get_room_messages(
        self,
        room_id: str,
        *,
        take: int = 50,
        before_utc: str | datetime | None = None,
    ) -> list[HarborMessage]:
        return list(self.get_room_messages_page(room_id, take=take, before_utc=before_utc).messages)

    def get_room_messages_page(
        self,
        room_id: str,
        *,
        take: int = 50,
        before_utc: str | datetime | None = None,
        after_message_id: str | None = None,
        cursor: str | None = None,
    ) -> HarborMessageBatch:
        payload = self.client.request(
            "GET",
            f"{BOT_API_PREFIX}/community-chat-rooms/{room_id}/messages",
            params=self.client.message_params(
                take,
                before_utc,
                after_message_id=after_message_id,
                cursor=cursor,
            ),
        )
        return self.client.message_batch_from_payload(payload, target_type="community", target_id=room_id)

    def send_room_message(
        self,
        room_id: str,
        text: str,
        *,
        media_id: str | None = None,
        reply_to_message_id: str | None = None,
        idempotency_key: str | None = None,
    ) -> dict[str, Any]:
        return self.client.request(
            "POST",
            f"{BOT_API_PREFIX}/community-chat-rooms/{room_id}/messages",
            json_body={
                "text": text,
                "mediaId": media_id,
                "replyToMessageId": reply_to_message_id,
            },
            idempotency_key=idempotency_key,
        )

    # Explicit aliases for readable application code.
    get_community_room_messages = get_room_messages
    send_community_room_message = send_room_message


@dataclass(frozen=True)
class CommandContext:
    """Data passed into router handlers."""

    bot: "HarborBot"
    message: HarborMessage
    target_type: TargetType
    target_id: str

    @property
    def command(self) -> str:
        return self.message.command_name()

    @property
    def args(self) -> str:
        return self.message.command_args()

    def operation_key(self, operation: str, *parts: object) -> str:
        raw_parts = [
            self.target_type,
            self.target_id,
            self.message.id or "no-message",
            operation or "operation",
            *(str(part) for part in parts if part is not None),
        ]
        safe_parts = [
            re.sub(r"[^A-Za-z0-9._~:-]+", "-", part.strip()).strip("-") or "part"
            for part in raw_parts
        ]
        return ":".join(safe_parts)[:240]

    def reply(self, text: str, *, idempotency_key: str | None = None) -> dict[str, Any]:
        return self.bot.send_message(
            self.target_type,
            self.target_id,
            text,
            reply_to_message_id=self.message.id,
            idempotency_key=idempotency_key,
        )

    def say(self, text: str, *, idempotency_key: str | None = None) -> dict[str, Any]:
        return self.bot.send_message(
            self.target_type,
            self.target_id,
            text,
            idempotency_key=idempotency_key,
        )


class HarborRouter:
    """Small message router for command and text handlers."""

    def __init__(self, *, prefix: str = "/", skip_bot_messages: bool = True) -> None:
        self.prefix = prefix
        self.skip_bot_messages = skip_bot_messages
        self._commands: dict[str, MessageCallback] = {}
        self._contains: list[tuple[tuple[str, ...], MessageCallback]] = []
        self._default: MessageCallback | None = None
        self._error_handler: ErrorCallback | None = None

    def command(self, name: str) -> Callable[[MessageCallback], MessageCallback]:
        def decorator(callback: MessageCallback) -> MessageCallback:
            self._commands[name.strip().lower()] = callback
            return callback

        return decorator

    def contains(self, *words: str) -> Callable[[MessageCallback], MessageCallback]:
        def decorator(callback: MessageCallback) -> MessageCallback:
            normalized = tuple(word for word in words if word)
            self._contains.append((normalized, callback))
            return callback

        return decorator

    def default(self, callback: MessageCallback) -> MessageCallback:
        self._default = callback
        return callback

    def error_handler(self, callback: ErrorCallback) -> ErrorCallback:
        self._error_handler = callback
        return callback

    def dispatch(self, context: CommandContext) -> HandlerResult:
        message = context.message
        if self.skip_bot_messages and message.author_is_bot:
            return None

        if message.is_command(self.prefix):
            callback = self._commands.get(message.command_name(self.prefix))
            if callback is not None:
                return callback(context)

        for words, callback in self._contains:
            if message.contains_any(list(words)):
                return callback(context)

        if self._default is not None:
            return self._default(context)
        return None

    def dispatch_error(self, context: CommandContext, error: Exception) -> HandlerErrorAction | None:
        if self._error_handler is None:
            return None
        return _normalize_handler_action(self._error_handler(context, error))


class PollingBot:
    """Long-running polling loop around HarborBot and HarborRouter."""

    def __init__(
        self,
        bot: "HarborBot",
        *,
        target_type: TargetType,
        target_id: str,
        router: HarborRouter,
        interval_seconds: float = 2.0,
        take: int = 50,
        cursor_store: CursorStore | None = None,
        error_handler: HarborErrorHandler | None = None,
    ) -> None:
        self.bot = bot
        self.target_type = target_type
        self.target_id = target_id
        self.router = router
        self.interval_seconds = interval_seconds
        self.take = take
        self.cursor_store = cursor_store or MemoryCursorStore()
        self.error_handler = error_handler or bot.errors

    @staticmethod
    def _install_signal_handlers(stop_event: threading.Event) -> list[tuple[signal.Signals, Any]]:
        if threading.current_thread() is not threading.main_thread():
            return []

        installed: list[tuple[signal.Signals, Any]] = []

        def request_stop(signum: int, _frame: Any) -> None:
            stop_event.set()

        for signal_name in ("SIGINT", "SIGTERM"):
            current_signal = getattr(signal, signal_name, None)
            if current_signal is None:
                continue
            try:
                previous = signal.getsignal(current_signal)
                signal.signal(current_signal, request_stop)
                installed.append((current_signal, previous))
            except (ValueError, OSError):
                continue
        return installed

    @staticmethod
    def _restore_signal_handlers(handlers: list[tuple[signal.Signals, Any]]) -> None:
        for current_signal, previous in reversed(handlers):
            try:
                signal.signal(current_signal, previous)
            except (ValueError, OSError):
                continue

    def run_forever(
        self,
        *,
        skip_existing: bool = True,
        stop_event: threading.Event | None = None,
        close_on_stop: bool = True,
        install_signal_handlers: bool = True,
    ) -> None:
        active_stop_event = stop_event or threading.Event()
        signal_handlers = self._install_signal_handlers(active_stop_event) \
            if install_signal_handlers else []
        current_skip_existing = skip_existing
        try:
            while not active_stop_event.is_set():
                try:
                    for message in self.bot.listen(
                        self.target_type,
                        self.target_id,
                        interval_seconds=self.interval_seconds,
                        take=self.take,
                        skip_existing=current_skip_existing,
                        cursor_store=self.cursor_store,
                        stop_event=active_stop_event,
                    ):
                        if active_stop_event.is_set():
                            break
                        current_skip_existing = False
                        context = CommandContext(
                            bot=self.bot,
                            message=message,
                            target_type=self.target_type,
                            target_id=self.target_id,
                        )
                        try:
                            self.router.dispatch(context)
                        except Exception as exc:
                            action = self.router.dispatch_error(context, exc)
                            if action is None:
                                action = self.error_handler.handle_callback_error(context, exc)
                            if action == "skip":
                                continue
                            if action == "stop":
                                active_stop_event.set()
                                break
                            raise HarborBotHandlerError(context, exc) from exc
                except KeyboardInterrupt:
                    active_stop_event.set()
                except Exception as exc:
                    if active_stop_event.is_set():
                        break
                    if not self.error_handler.should_continue(exc):
                        raise
                    current_skip_existing = False
                    if _sleep_or_stop(self.interval_seconds, active_stop_event):
                        break
        finally:
            self._restore_signal_handlers(signal_handlers)
            if close_on_stop:
                self.bot.close()


class HarborBot:
    """Official Python runtime client for Harbor bots.

    The client accepts only a Harbor bot token. It does not support account
    login, email/password auth, or user JWT automation.
    """

    DEFAULT_BASE_URL = "https://harborproject.ru"

    def __init__(
        self,
        token: str | BotTokenAuth,
        *,
        base_url: str = DEFAULT_BASE_URL,
        timeout: float = 30,
        allow_unsafe_base_url: bool = False,
        session: requests.Session | None = None,
        logger: logging.Logger | None = None,
        retry_max_attempts: int = 4,
        retry_backoff_base: float = 1.0,
        retry_backoff_max: float = 60.0,
        retry_jitter: float = 0.25,
    ) -> None:
        self.auth = token if isinstance(token, BotTokenAuth) else BotTokenAuth(token)
        self.base_url = _validate_base_url_for_token(
            base_url,
            self.auth,
            allow_unsafe_base_url=allow_unsafe_base_url,
        )
        self.timeout = _coerce_positive_float("timeout", timeout)
        self.retry_max_attempts = max(1, int(retry_max_attempts))
        self.retry_backoff_base = _coerce_positive_float("retry_backoff_base", retry_backoff_base)
        self.retry_backoff_max = _coerce_positive_float("retry_backoff_max", retry_backoff_max)
        self.retry_jitter = max(0.0, float(retry_jitter))
        self.session = session or requests.Session()
        self.logger = logger or logging.getLogger("HarborBot")
        self.errors = HarborErrorHandler(logger=self.logger)
        self.chat = HarborChatApi(self)
        self.community = HarborCommunityApi(self)

    @classmethod
    def from_env(cls, *, allow_unsafe_base_url: bool = False) -> "HarborBot":
        """Create a client from HARBOR_BOT_TOKEN and optional HARBOR_BASE_URL."""

        config = HarborRuntimeConfig.from_env()
        return cls(
            token=config.token,
            base_url=config.base_url,
            timeout=config.timeout,
            allow_unsafe_base_url=allow_unsafe_base_url,
        )

    @classmethod
    def from_config(
        cls,
        config: HarborRuntimeConfig,
        *,
        allow_unsafe_base_url: bool = False,
    ) -> "HarborBot":
        return cls(
            token=config.token,
            base_url=config.base_url,
            timeout=config.timeout,
            allow_unsafe_base_url=allow_unsafe_base_url,
        )

    def close(self) -> None:
        close = getattr(self.session, "close", None)
        if callable(close):
            close()

    def __enter__(self) -> "HarborBot":
        return self

    def __exit__(self, _exc_type: Any, _exc: Any, _traceback: Any) -> None:
        self.close()

    @property
    def token(self) -> str:
        return self.auth.token

    @property
    def headers(self) -> dict[str, str]:
        headers = dict(self.auth.headers)
        headers.update(
            {
                "User-Agent": SDK_USER_AGENT,
                "X-Harbor-SDK-Version": __version__,
                "X-Harbor-API-Version": API_VERSION,
            }
        )
        return headers

    def get_targets(self) -> list[BotRuntimeTarget]:
        """Return chats and rooms currently available to this bot token."""

        payload = self.request("GET", f"{BOT_API_PREFIX}/targets")
        if not isinstance(payload, dict):
            return []

        items = payload.get("items")
        if not isinstance(items, list):
            return []

        targets: list[BotRuntimeTarget] = []
        for item in items:
            if isinstance(item, dict):
                targets.append(BotRuntimeTarget.from_payload(item))
        return targets

    def get_invites(self) -> list[BotRuntimeInvite]:
        """Return pending community-room invites for this bot token."""

        payload = self.request("GET", f"{BOT_API_PREFIX}/invites")
        if not isinstance(payload, dict):
            return []

        items = payload.get("items")
        if not isinstance(items, list):
            return []

        invites: list[BotRuntimeInvite] = []
        for item in items:
            if isinstance(item, dict):
                invites.append(BotRuntimeInvite.from_payload(item))
        return invites

    def accept_invite(self, target_id: str) -> BotRuntimeTarget:
        """Accept a pending community-room invite and return the active target."""

        room_id = (target_id or "").strip()
        if not room_id:
            raise HarborBotConfigError("invite target_id is required")

        payload = self.request("POST", f"{BOT_API_PREFIX}/invites/{room_id}/accept")
        if not isinstance(payload, dict):
            raise HarborBotConfigError("accept invite response must be a JSON object")
        return BotRuntimeTarget.from_payload(payload)

    def select_invite(
        self,
        *,
        preferred_type: TargetType | None = "community",
        target_id: str | None = None,
        community_id: str | None = None,
        required_scopes: tuple[str, ...] | list[str] = ("chat:read", "chat:write"),
    ) -> BotRuntimeInvite:
        """Pick one pending invite matching type, ids, and required scopes."""

        invites = self.get_invites()
        if preferred_type is not None:
            invites = [invite for invite in invites if invite.runtime_type == preferred_type]
        if target_id:
            expected_target_id = target_id.strip().lower()
            invites = [invite for invite in invites if invite.target_id.lower() == expected_target_id]
        if community_id:
            expected_community_id = community_id.strip().lower()
            invites = [
                invite for invite in invites
                if (invite.community_id or "").lower() == expected_community_id
            ]

        required = tuple(scope.lower() for scope in required_scopes)
        if required:
            invites = [
                invite for invite in invites
                if all(invite.has_scope(scope) for scope in required)
            ]

        if not invites:
            type_hint = f" with runtime_type={preferred_type}" if preferred_type else ""
            scope_hint = f" and scopes={', '.join(required)}" if required else ""
            raise HarborBotConfigError(f"No pending bot invites{type_hint}{scope_hint}.")

        if len(invites) > 1:
            raise HarborBotAmbiguousTargetError(
                f"Found {len(invites)} matching invites. Specify target_id."
            )

        return invites[0]

    def select_target(
        self,
        *,
        preferred_type: TargetType | None = None,
        target_id: str | None = None,
        community_id: str | None = None,
        required_scopes: tuple[str, ...] | list[str] = ("chat:read", "chat:write"),
    ) -> BotRuntimeTarget:
        """Pick one available target matching type, ids, and required scopes."""

        targets = self.get_targets()
        if preferred_type is not None:
            targets = [target for target in targets if target.runtime_type == preferred_type]
        if target_id:
            expected_target_id = target_id.strip().lower()
            targets = [target for target in targets if target.target_id.lower() == expected_target_id]
        if community_id:
            expected_community_id = community_id.strip().lower()
            targets = [
                target for target in targets
                if (target.community_id or "").lower() == expected_community_id
            ]

        required = tuple(scope.lower() for scope in required_scopes)
        if required:
            targets = [
                target for target in targets
                if all(target.has_scope(scope) for scope in required)
            ]

        if not targets:
            type_hint = f" with runtime_type={preferred_type}" if preferred_type else ""
            scope_hint = f" and scopes={', '.join(required)}" if required else ""
            raise HarborBotConfigError(f"No available bot targets{type_hint}{scope_hint}.")

        if len(targets) > 1:
            raise HarborBotAmbiguousTargetError(
                f"Found {len(targets)} matching targets. Specify target_id."
            )

        return targets[0]

    def get_global_messages(
        self,
        chat_id: str,
        *,
        take: int = 50,
        before_utc: str | datetime | None = None,
    ) -> list[HarborMessage]:
        return self.chat.get_global_messages(chat_id, take=take, before_utc=before_utc)

    def send_global_message(
        self,
        chat_id: str,
        text: str,
        *,
        media_id: str | None = None,
        reply_to_message_id: str | None = None,
        idempotency_key: str | None = None,
    ) -> dict[str, Any]:
        return self.chat.send_global_message(
            chat_id,
            text,
            media_id=media_id,
            reply_to_message_id=reply_to_message_id,
            idempotency_key=idempotency_key,
        )

    def get_community_room_messages(
        self,
        room_id: str,
        *,
        take: int = 50,
        before_utc: str | datetime | None = None,
    ) -> list[HarborMessage]:
        return self.community.get_room_messages(room_id, take=take, before_utc=before_utc)

    def send_community_room_message(
        self,
        room_id: str,
        text: str,
        *,
        media_id: str | None = None,
        reply_to_message_id: str | None = None,
        idempotency_key: str | None = None,
    ) -> dict[str, Any]:
        return self.community.send_room_message(
            room_id,
            text,
            media_id=media_id,
            reply_to_message_id=reply_to_message_id,
            idempotency_key=idempotency_key,
        )

    def get_messages(
        self,
        target_type: TargetType,
        target_id: str,
        *,
        take: int = 50,
        before_utc: str | datetime | None = None,
    ) -> list[HarborMessage]:
        return self.chat.get_messages(target_type, target_id, take=take, before_utc=before_utc)

    def get_messages_page(
        self,
        target_type: TargetType,
        target_id: str,
        *,
        take: int = 50,
        before_utc: str | datetime | None = None,
        after_message_id: str | None = None,
        cursor: str | None = None,
    ) -> HarborMessageBatch:
        return self.chat.get_messages_page(
            target_type,
            target_id,
            take=take,
            before_utc=before_utc,
            after_message_id=after_message_id,
            cursor=cursor,
        )

    def send_message(
        self,
        target_type: TargetType,
        target_id: str,
        text: str,
        *,
        media_id: str | None = None,
        reply_to_message_id: str | None = None,
        idempotency_key: str | None = None,
    ) -> dict[str, Any]:
        return self.chat.send_message(
            target_type,
            target_id,
            text,
            media_id=media_id,
            reply_to_message_id=reply_to_message_id,
            idempotency_key=idempotency_key,
        )

    def listen(
        self,
        target_type: TargetType,
        target_id: str,
        *,
        interval_seconds: float = 2.0,
        take: int = 50,
        skip_existing: bool = True,
        cursor_store: CursorStore | None = None,
        initial_after_message_id: str | None = None,
        stop_event: threading.Event | None = None,
    ) -> Iterator[HarborMessage]:
        """Poll a chat and yield messages using at-least-once delivery."""

        seen: set[str] = set()
        seen_order: deque[str] = deque()
        checkpoint = (initial_after_message_id or "").strip() or None
        if checkpoint is None and cursor_store is not None:
            checkpoint = cursor_store.load(target_type, target_id)
        first_tick = checkpoint is None and skip_existing

        def remember(message_id: str) -> None:
            if message_id in seen:
                return
            seen.add(message_id)
            seen_order.append(message_id)
            while len(seen_order) > 5000:
                old_id = seen_order.popleft()
                seen.discard(old_id)

        def save_checkpoint(message_id: str) -> None:
            nonlocal checkpoint
            checkpoint = message_id
            if cursor_store is not None:
                cursor_store.save(target_type, target_id, message_id)
            self.logger.debug(
                "Harbor checkpoint saved",
                extra=safe_log_extra(
                    "checkpoint_saved",
                    target_type=target_type,
                    target_id=target_id,
                    message_id=message_id,
                    cursor=message_id,
                ),
            )

        while not _is_stopped(stop_event):
            page = self.get_messages_page(
                target_type,
                target_id,
                take=take,
                after_message_id=checkpoint,
            )
            messages = list(page.messages)

            if first_tick and skip_existing:
                for message in messages:
                    if message.id:
                        remember(message.id)
                        save_checkpoint(message.id)
                first_tick = False
                if page.has_more and messages:
                    continue
                if _sleep_or_stop(interval_seconds, stop_event):
                    return
                continue

            first_tick = False
            yielded_any = False
            for message in messages:
                if _is_stopped(stop_event):
                    return
                if not message.id or message.id in seen:
                    continue
                yield message
                remember(message.id)
                save_checkpoint(message.id)
                yielded_any = True

            if page.has_more and yielded_any:
                continue

            if not page.has_more or not yielded_any:
                if _sleep_or_stop(interval_seconds, stop_event):
                    return

    def app(
        self,
        *,
        target_type: TargetType,
        target_id: str,
        router: HarborRouter,
        interval_seconds: float = 2.0,
        take: int = 50,
        cursor_store: CursorStore | None = None,
    ) -> PollingBot:
        return PollingBot(
            self,
            target_type=target_type,
            target_id=target_id,
            router=router,
            interval_seconds=interval_seconds,
            take=take,
            cursor_store=cursor_store,
        )

    def request(
        self,
        method: str,
        path: str,
        *,
        params: dict[str, Any] | None = None,
        json_body: dict[str, Any] | None = None,
        idempotency_key: str | None = None,
    ) -> Any:
        method_upper = method.upper()
        headers = self.headers
        if idempotency_key is not None:
            if not isinstance(idempotency_key, str) or not 1 <= len(idempotency_key) <= 256 or any(
                not "!" <= ch <= "~" or ch == "," for ch in idempotency_key
            ):
                raise HarborBotConfigError("idempotency_key must contain 1-256 printable ASCII characters, excluding commas")
            headers["Idempotency-Key"] = idempotency_key

        can_retry = method_upper == "GET"
        response: requests.Response | None = None

        for attempt in range(self.retry_max_attempts):
            attempt_number = attempt + 1
            started_at = time.monotonic()
            try:
                response = self.session.request(
                    method_upper,
                    f"{self.base_url}{path}",
                    headers=headers,
                    params=params,
                    json=json_body,
                    timeout=self.timeout,
                )
            except requests.RequestException as exc:
                duration_ms = _duration_ms(started_at)
                self.logger.warning(
                    "Harbor request transport error: method=%s attempt=%s error=%s",
                    method_upper,
                    attempt_number,
                    exc.__class__.__name__,
                    extra=safe_log_extra(
                        "transport_error",
                        method=method_upper,
                        attempt=attempt_number,
                        duration_ms=duration_ms,
                        idempotency_key=idempotency_key,
                        error_type=exc.__class__.__name__,
                    ),
                )
                if not can_retry or attempt >= self.retry_max_attempts - 1:
                    raise
                delay = self.sleep_before_retry(attempt)
                self.logger.info(
                    "Harbor request retry scheduled: method=%s attempt=%s retry_after=%ss",
                    method_upper,
                    attempt_number,
                    delay,
                    extra=safe_log_extra(
                        "request_retry",
                        method=method_upper,
                        attempt=attempt_number,
                        retry_after=delay,
                        duration_ms=duration_ms,
                        idempotency_key=idempotency_key,
                    ),
                )
                continue

            duration_ms = _duration_ms(started_at)
            retry_after = self.retry_after(response)
            if response.status_code == 429 and can_retry and attempt < self.retry_max_attempts - 1:
                delay = self.sleep_before_retry(attempt, retry_after_seconds=retry_after)
                self.logger.info(
                    "Harbor request retry scheduled: method=%s status=%s attempt=%s retry_after=%ss",
                    method_upper,
                    response.status_code,
                    attempt_number,
                    delay,
                    extra=safe_log_extra(
                        "request_retry",
                        method=method_upper,
                        attempt=attempt_number,
                        status_code=response.status_code,
                        retry_after=delay,
                        duration_ms=duration_ms,
                        idempotency_key=idempotency_key,
                    ),
                )
                continue

            if response.status_code in {502, 503, 504} and can_retry and attempt < self.retry_max_attempts - 1:
                delay = self.sleep_before_retry(attempt, retry_after_seconds=retry_after)
                self.logger.info(
                    "Harbor request retry scheduled: method=%s status=%s attempt=%s retry_after=%ss",
                    method_upper,
                    response.status_code,
                    attempt_number,
                    delay,
                    extra=safe_log_extra(
                        "request_retry",
                        method=method_upper,
                        attempt=attempt_number,
                        status_code=response.status_code,
                        retry_after=delay,
                        duration_ms=duration_ms,
                        idempotency_key=idempotency_key,
                    ),
                )
                continue

            self.logger.debug(
                "Harbor request finished: method=%s status=%s attempt=%s duration_ms=%s",
                method_upper,
                response.status_code,
                attempt_number,
                duration_ms,
                extra=safe_log_extra(
                    "request_finished",
                    method=method_upper,
                    attempt=attempt_number,
                    status_code=response.status_code,
                    retry_after=retry_after,
                    duration_ms=duration_ms,
                    idempotency_key=idempotency_key,
                ),
            )
            break

        if response is None:
            raise RuntimeError("Request did not produce a response")

        if response.status_code == 429:
            raise HarborBotRateLimitError(self.retry_after(response), response.text)
        if response.status_code >= 400:
            message, code = self.error_details(response)
            error_cls: type[HarborBotApiError]
            if response.status_code == 401:
                error_cls = HarborBotUnauthorizedError
            elif response.status_code == 403:
                error_cls = HarborBotForbiddenError
            elif response.status_code == 404:
                error_cls = HarborBotNotFoundError
            elif response.status_code == 409:
                error_cls = HarborBotConflictError
            else:
                error_cls = HarborBotApiError
            raise error_cls(
                response.status_code,
                message,
                code=code,
                response_text=response.text,
            )
        if not response.content:
            return None
        if "json" in response.headers.get("content-type", "").lower():
            return response.json()
        return response.text

    @staticmethod
    def message_params(
        take: int,
        before_utc: str | datetime | None,
        *,
        after_message_id: str | None = None,
        cursor: str | None = None,
    ) -> dict[str, Any]:
        if before_utc is not None and (after_message_id or cursor):
            raise HarborBotConfigError("before_utc cannot be used together with after_message_id or cursor")

        params: dict[str, Any] = {"take": max(1, min(int(take), 100))}
        if before_utc is not None:
            if isinstance(before_utc, datetime):
                value = before_utc
                if value.tzinfo is None:
                    value = value.replace(tzinfo=timezone.utc)
                params["beforeUtc"] = value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
            else:
                params["beforeUtc"] = before_utc
        if after_message_id:
            params["afterMessageId"] = after_message_id
        if cursor:
            params["cursor"] = cursor
        return params

    @staticmethod
    def message_batch_from_payload(
        payload: Any,
        *,
        target_type: TargetType | None = None,
        target_id: str | None = None,
    ) -> HarborMessageBatch:
        if not isinstance(payload, dict):
            return HarborMessageBatch(())
        messages = payload.get("messages")
        parsed = tuple(
            HarborMessage(raw=item, target_type=target_type, target_id=target_id)
            for item in messages
            if isinstance(item, dict)
        ) if isinstance(messages, list) else ()
        cursor = payload.get("cursor")
        continuation_token = payload.get("continuationToken")
        return HarborMessageBatch(
            parsed,
            str(cursor) if cursor else None,
            str(continuation_token) if continuation_token else None,
            bool(payload.get("hasMore")),
        )

    @staticmethod
    def messages_from_payload(
        payload: Any,
        *,
        target_type: TargetType | None = None,
        target_id: str | None = None,
    ) -> list[HarborMessage]:
        if not isinstance(payload, dict):
            return []
        messages = payload.get("messages")
        if not isinstance(messages, list):
            return []
        return list(
            HarborBot.message_batch_from_payload(
                payload,
                target_type=target_type,
                target_id=target_id,
            ).messages
        )

    @staticmethod
    def retry_after(response: requests.Response) -> int | None:
        raw = response.headers.get("Retry-After")
        if not raw:
            return None
        value = raw.strip()
        try:
            return max(0, int(value))
        except ValueError:
            pass

        try:
            retry_at = parsedate_to_datetime(value)
        except (TypeError, ValueError, IndexError, OverflowError):
            return None
        if retry_at.tzinfo is None:
            retry_at = retry_at.replace(tzinfo=timezone.utc)
        seconds = (retry_at.astimezone(timezone.utc) - datetime.now(timezone.utc)).total_seconds()
        return max(0, math.ceil(seconds))

    def retry_delay(self, attempt: int) -> float:
        base = min(self.retry_backoff_max, self.retry_backoff_base * (2 ** max(0, attempt)))
        if self.retry_jitter <= 0:
            return base
        jitter = random.uniform(0, min(self.retry_jitter, base))
        return min(self.retry_backoff_max, base + jitter)

    def sleep_before_retry(self, attempt: int, *, retry_after_seconds: int | None = None) -> float:
        if retry_after_seconds is not None:
            delay = max(0, retry_after_seconds)
            time.sleep(delay)
            return float(delay)
        delay = self.retry_delay(attempt)
        time.sleep(delay)
        return float(delay)

    @staticmethod
    def error_details(response: requests.Response) -> tuple[str, str | None]:
        try:
            payload = response.json()
        except ValueError:
            return response.text or response.reason, None

        if isinstance(payload, dict):
            code = payload.get("code") or payload.get("errorCode")
            message = (
                payload.get("message")
                or payload.get("title")
                or payload.get("detail")
                or response.reason
            )
            return str(message), str(code) if code else None
        return response.text or response.reason, None
