"""
quizlib multiple choice question type
"""

from collections.abc import Sequence
from dataclasses import dataclass, field

from quizlib.types import MCAnswer, QuestionType


@dataclass
class MultipleChoice:
    """Multiple choice question.

    Supports single answer (radio buttons) or multiple answers (checkboxes).
    The mode is automatically determined by the number of correct answers.

    Attributes:
        name: Question identifier/title.
        text: Question text in Markdown format.
        answers: Sequence of (is_correct, answer_text) tuples.
                 Accepts list or tuple. is_correct is 1 for correct, 0 for incorrect.
        defgrade: Points for this question. Defaults to number of correct answers.
    """

    name: str
    text: str
    answers: Sequence[MCAnswer]
    defgrade: int | float | None = None
    typ: QuestionType = field(default=QuestionType.MULTIPLE_CHOICE, init=False)

    def __post_init__(self) -> None:
        if not isinstance(self.answers, list):
            object.__setattr__(self, "answers", list(self.answers))
        if self.defgrade is None:
            self.defgrade = self.n_correct

    @property
    def n_correct(self) -> int:
        """Number of correct answers."""
        return sum(1 for is_correct, _ in self.answers if is_correct == 1)

    @property
    def is_single(self) -> bool:
        """True if only one answer is correct (radio button mode)."""
        return self.n_correct == 1


# Backwards-compatible alias
MC = MultipleChoice
