"""Short pairing code helpers for worker onboarding."""

from __future__ import annotations

import secrets


PAIRING_CODE_LENGTH = 6
PAIRING_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"


class InviteCodeError(ValueError):
    """Raised when a pairing code cannot be validated."""


def generate_pairing_code(length: int = PAIRING_CODE_LENGTH) -> str:
    if length < 1:
        raise ValueError("pairing code length must be positive")
    return "".join(secrets.choice(PAIRING_ALPHABET) for _ in range(length))


def validate_pairing_code(code: str) -> str:
    normalized = code.strip().upper()
    if len(normalized) != PAIRING_CODE_LENGTH:
        raise InviteCodeError("pairing code must be 6 characters")
    invalid = sorted(set(normalized) - set(PAIRING_ALPHABET))
    if invalid:
        joined = ", ".join(invalid)
        raise InviteCodeError(f"pairing code contains invalid character(s): {joined}")
    return normalized


def create_invite_code(*args: object, **kwargs: object) -> str:
    """Backward-compatible name for the new short pairing code generator."""
    return generate_pairing_code()


def parse_invite_code(invite_code: str) -> dict[str, str]:
    """Validate a short pairing code and return a small normalized payload."""
    return {"code": validate_pairing_code(invite_code)}
