from django import forms
from django.utils.translation import gettext_lazy as _

from servala.core.models import ControlPlane, ServiceDefinition


class ControlPlaneAdminForm(forms.ModelForm):
    certificate_authority_data = forms.CharField(
        widget=forms.Textarea,
        required=False,
        help_text=_("Certificate authority data for the Kubernetes API"),
    )
    server = forms.URLField(
        required=False,
        help_text=_("Server URL for the Kubernetes API"),
    )
    token = forms.CharField(
        widget=forms.Textarea,
        required=False,
        help_text=_("Authentication token for the Kubernetes API"),
    )

    class Meta:
        model = ControlPlane
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # If we have existing api_credentials, populate the individual fields
        if self.instance.pk and self.instance.api_credentials:
            creds = self.instance.api_credentials
            self.fields["certificate_authority_data"].initial = creds.get(
                "certificate-authority-data", ""
            )
            self.fields["server"].initial = creds.get("server", "")
            self.fields["token"].initial = creds.get("token", "")

    def clean(self):
        cleaned_data = super().clean()

        ca_data = cleaned_data.get("certificate_authority_data")
        server = cleaned_data.get("server")
        token = cleaned_data.get("token")

        if ca_data and server and token:
            cleaned_data["api_credentials"] = {
                "certificate-authority-data": ca_data,
                "server": server,
                "token": token,
            }
        else:
            if not (ca_data or server or token):
                cleaned_data["api_credentials"] = {}
            else:
                # Some fields are filled but not all - validation will fail at model level,
                # as model field validators are also called by the API.
                # We still create the JSON with whatever we have so the model validator can run.
                credentials = {}
                if ca_data:
                    credentials["certificate-authority-data"] = ca_data
                if server:
                    credentials["server"] = server
                if token:
                    credentials["token"] = token
                cleaned_data["api_credentials"] = credentials

        return cleaned_data

    def save(self, *args, **kwargs):
        self.instance.api_credentials = self.cleaned_data["api_credentials"]
        return super().save(*args, **kwargs)


class ServiceDefinitionAdminForm(forms.ModelForm):
    api_group = forms.CharField(
        required=False,
        help_text=_("API Group"),
    )
    api_version = forms.CharField(
        required=False,
        help_text=_("API Version"),
    )
    api_kind = forms.CharField(
        required=False,
        help_text=_("API Kind"),
    )

    class Meta:
        model = ServiceDefinition
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # If we have existing api_definition, populate the individual fields
        if self.instance.pk and self.instance.api_definition:
            api_def = self.instance.api_definition
            self.fields["api_group"].initial = api_def.get("group", "")
            self.fields["api_version"].initial = api_def.get("version", "")
            self.fields["api_kind"].initial = api_def.get("kind", "")

    def clean(self):
        cleaned_data = super().clean()

        api_group = cleaned_data.get("api_group")
        api_version = cleaned_data.get("api_version")
        api_kind = cleaned_data.get("api_kind")

        if api_group and api_version and api_kind:
            cleaned_data["api_definition"] = {
                "group": api_group,
                "version": api_version,
                "kind": api_kind,
            }
        else:
            if not (api_group or api_version or api_kind):
                cleaned_data["api_definition"] = {}
            else:
                # Some fields are filled but not all – validation will fail at model level.
                api_def = {}
                if api_group:
                    api_def["group"] = api_group
                if api_version:
                    api_def["version"] = api_version
                if api_kind:
                    api_def["kind"] = api_kind
                cleaned_data["api_definition"] = api_def

        return cleaned_data

    def save(self, *args, **kwargs):
        self.instance.api_definition = self.cleaned_data["api_definition"]
        return super().save(*args, **kwargs)
