"""
quizli quiz container class
"""

from __future__ import annotations

import re
from collections.abc import Callable, Iterable, Iterator
from dataclasses import dataclass, field
from typing import Any

from quizlib.questions.base import Question


@dataclass
class Quiz:
    """A collection of quiz questions with builder pattern support."""

    category: str
    info: str = ""
    questions: list[Question] = field(default_factory=list)

    def add(self, question: Question) -> Quiz:
        """Add a question. Returns self for chaining."""
        self.questions.append(question)
        return self

    def add_all(self, questions: Iterable[Question]) -> Quiz:
        """Add multiple questions. Returns self for chaining."""
        self.questions.extend(questions)
        return self

    def sort(
        self,
        *,
        key: Callable[[Question], Any] | None = None,
        reverse: bool = False,
    ) -> Quiz:
        """Sort questions in place. Default key is name. Returns self for chaining."""
        self.questions.sort(key=key or (lambda q: q.name), reverse=reverse)
        return self

    def filter(self, pattern: str) -> Quiz:
        """Return a NEW Quiz with only questions matching the regex pattern."""
        regex = re.compile(pattern)
        filtered = [q for q in self.questions if regex.search(q.name)]
        return Quiz(
            category=self.category,
            info=self.info,
            questions=filtered,
        )

    def to_xml(self) -> str:
        """Render the quiz to Moodle XML format."""
        from quizlib.renderers import MoodleXMLRenderer

        return MoodleXMLRenderer().render(self)

    def to_markdown(self) -> str:
        """Render the quiz to Markdown format."""
        from quizlib.renderers import MarkdownRenderer

        return MarkdownRenderer().render(self)

    def __len__(self) -> int:
        """Number of questions in the quiz."""
        return len(self.questions)

    def __iter__(self) -> Iterator[Question]:
        """Iterate over questions."""
        return iter(self.questions)
