from __future__ import annotations

from typing import TYPE_CHECKING, Any

from django import forms

if TYPE_CHECKING:
    from ..model_mixins import VisitModelMixin


def get_related_visit(
    modelform: Any, related_visit_model_attr: str = None
) -> VisitModelMixin | None:
    """Returns the related visit mode instance or None."""
    if related_visit_model_attr not in modelform.cleaned_data:
        related_visit = modelform.instance.related_visit
        if not related_visit:
            raise forms.ValidationError(f"Field `{related_visit_model_attr}` is required (2).")
    else:
        related_visit = modelform.cleaned_data.get(related_visit_model_attr)
    return related_visit
