import os
from dataclasses import dataclass
from typing import Callable

from analyst_klondike.features.data_context.data_state import DataState
from analyst_klondike.features.err_handling import catch_error
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 CreateFileAction(BaseAction):
    type = "CREATE_FILE_ACTION"
    file_name: str


def apply(state: AppState, action: BaseAction) -> AppState:
    if isinstance(action, CreateFileAction):

        state.current.opened_file_path = os.path.join(
            state.current.working_directory, action.file_name + ".yaml"
        )
        state.current.opened_file_name = action.file_name
        state.data = DataState()
        # if no file not yet opened, then we need to set version
        state.current.opened_file_min_supported_app_version = state.current.app_version
        return state
    return state


@catch_error
def push_screen(dismiss_callback: Callable[[str | None], None]):

    def _check_file(title: str) -> bool:
        state = get_state()
        file_name = os.path.join(
            state.current.working_directory, title + ".yaml"
        )
        return not os.path.exists(file_name)

    push_create_edit_screen(
        dismiss_callback,
        "Создать файл",
        _check_file
    )


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