from __future__ import annotations

from typing import TYPE_CHECKING, Callable, Optional

from pydantic import BaseModel, Extra, Field

from ..types import Widget
from .utils import Executable

if TYPE_CHECKING:
    from .._command_registry import CommandRegistry


class WidgetContribution(BaseModel, Executable[Widget]):
    command: str = Field(
        ..., description="Identifier of a command that returns a Widget instance."
    )
    display_name: str = Field(
        ..., description="Name of the widget that will be presented in the display."
    )
    autogenerate: bool = Field(
        default=False,
        description="If true, a widget will be autogenerated from "
        "the type signature of the provided command with magicgui.",
    )

    class Config:
        extra = Extra.forbid

    def get_callable(
        self, _registry: Optional[CommandRegistry] = None
    ) -> Callable[..., Widget]:
        func = super().get_callable()
        if self.autogenerate:
            from magicgui import magic_factory

            return magic_factory(func)
        return func
