"""Forms for the MCP token self-service dashboard."""

from __future__ import annotations

import asyncio
import functools

from django import forms

from .models import MCPToken


@functools.lru_cache(maxsize=1)
def _registered_tool_names() -> list[str]:
    """Pull the list of registered MCP tool names from the FastMCP instance.

    Cached at module level — the tool registry is fixed at server startup.
    Importing here (rather than at module import) avoids circulars when the
    server module imports the dashboard pieces transitively.
    """
    from .server import mcp

    tools = asyncio.run(mcp.get_tools())
    return sorted(tools.keys())


def _tool_choices() -> list[tuple[str, str]]:
    return [(name, name) for name in _registered_tool_names()]


class MCPTokenCreateForm(forms.Form):
    """Generate a new bearer token. The token value itself is server-generated."""

    name = forms.CharField(
        max_length=100,
        widget=forms.TextInput(attrs={
            "class": "input input-bordered w-full",
            "placeholder": "e.g. Claude Desktop, CI script",
        }),
    )
    expires_at = forms.DateTimeField(
        required=False,
        widget=forms.DateTimeInput(attrs={
            "class": "input input-bordered w-full",
            "type": "datetime-local",
        }),
        help_text="Leave blank for no expiry.",
    )
    allowed_tools = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple(attrs={"class": "checkbox checkbox-sm"}),
        help_text="Leave all unchecked to permit every tool.",
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["allowed_tools"].choices = _tool_choices()


class MCPTokenEditForm(forms.ModelForm):
    """Edit token metadata. The hashed token itself cannot be edited."""

    allowed_tools = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple(attrs={"class": "checkbox checkbox-sm"}),
        help_text="Leave all unchecked to permit every tool.",
    )

    class Meta:
        model = MCPToken
        fields = ["name", "is_active", "expires_at", "allowed_tools"]
        widgets = {
            "name": forms.TextInput(attrs={"class": "input input-bordered w-full"}),
            "is_active": forms.CheckboxInput(attrs={"class": "toggle toggle-primary"}),
            "expires_at": forms.DateTimeInput(attrs={
                "class": "input input-bordered w-full",
                "type": "datetime-local",
            }),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["allowed_tools"].choices = _tool_choices()
        if self.instance and self.instance.pk:
            self.fields["allowed_tools"].initial = self.instance.allowed_tools or []
