from dataclasses import dataclass
from typing import Callable

from analyst_klondike.features.data_context.data_state import PythonQuizState
from analyst_klondike.features.teacher.create_screen.screen import push_create_edit_screen
from analyst_klondike.state.app_state import AppState, get_state
from analyst_klondike.state.base_action import BaseAction


@dataclass
class CreateQuizAction(BaseAction):
    type = "CREATE_QUIZ_ACTION"
    quiz_name: str


def apply(state: AppState, action: BaseAction) -> AppState:
    if isinstance(action, CreateQuizAction):
        if action.quiz_name in state.data.quizes:
            existed_quiz_ids = ", ".join(state.data.quizes.keys())
            raise KeyError(
                f"Quiz with id = {action.quiz_name} already exists: {existed_quiz_ids}"
            )

        new_quiz = PythonQuizState(
            id=action.quiz_name,
            title=action.quiz_name,
            is_node_expanded=False
        )
        state.data.quizes[action.quiz_name] = new_quiz
        return state
    return state


def push_screen(dismiss_callback: Callable[[str | None], None]):
    def _is_title_unique(value: str) -> bool:
        state = get_state()
        return value not in state.data.quizes
    push_create_edit_screen(dismiss_callback, "Создать тест", _is_title_unique)


__all__ = [
    "CreateQuizAction",
    "apply",
    "push_screen"
]
