from __future__ import annotations

from typing import Annotated, Any, Literal, Union

from pydantic import BaseModel, ConfigDict, Field


class BaseTemplate(BaseModel):
    model_config = ConfigDict(
        serialize_by_alias=True,
        validate_by_name=True,
        validate_by_alias=False,
    )
    name: str
    label: str


class HiddenTemplate(BaseTemplate):
    type: Literal["hidden"]
    initial_value: str = Field(alias="initialValue")


class TextTemplate(BaseTemplate):
    type: Literal["text"]
    editable: bool = True
    required: bool = True


class TextListTemplate(BaseTemplate):
    type: Literal["text-list"]
    editable: bool = True
    required: bool = True


class GroupTemplate(BaseTemplate):
    type: Literal["group"]
    children: list["Template"] = Field(default_factory=list)
    editable: bool = True
    required: bool = True

    def model_post_init(self, context: Any, /) -> None:
        identifier = HiddenTemplate(
            type="hidden",
            name="identifier",
            label="identifier",
            initial_value="uuid4",
        )
        self.children.insert(0, identifier)


Template = Annotated[
    Union[HiddenTemplate, TextTemplate, TextListTemplate, GroupTemplate],
    Field(discriminator="type"),
]
