"""Agent creation modal for creating new agents.

Provides a comprehensive modal screen that allows users to create a new agent
with all required fields: name, models, tags, and optional configuration.
"""

from typing import Any

from alloy_runtime_sdk.api_client.client import ApiClient
from alloy_runtime_types.dtos.agents import CreateAgentRequest

from cli.infrastructure.forms.agent_picker import AgentPicker
from cli.infrastructure.forms.schema_picker import SchemaPicker
from cli.infrastructure.forms.tag_picker import TagPicker
from cli.infrastructure.forms.template_picker import TemplatePicker
from cli.tui.widgets.agent_form_modal import AgentFormModal, AgentFormResult


class AgentCreateModal(AgentFormModal):
    """Modal for creating a new agent.

    Provides a comprehensive form with:
    - Required fields: name, models, tags
    - Basic info: description, scope, base agent
    - System instruction: template picker
    - Schemas: input/output schema pickers or inline JSON schema builder
    - Generation parameters: temperature, max_tokens, etc.
    - Advanced: default headers with quick-add buttons

    Usage:
        def on_agent_created(result: AgentCreateResult | None):
            if result is not None:
                self.notify(f"Created agent: {result.agent_name}")
                self._do_search("")  # Refresh list

        client = await self.app.store.get_client()
        self.app.push_screen(
            AgentCreateModal(client=client),
            on_agent_created
        )
    """

    def __init__(
        self,
        client: ApiClient,
        **kwargs: Any,
    ) -> None:
        """Initialize the agent creation modal.

        Args:
            client: ApiClient instance for API calls
        """
        super().__init__(client=client, **kwargs)

    def _get_modal_title(self) -> str:
        """Return the modal title."""
        return "Create New Agent"

    def _get_submit_button_text(self) -> str:
        """Return the submit button text."""
        return "Create Agent"

    def _is_scope_editable(self) -> bool:
        """Return whether the scope can be changed."""
        return True

    async def _submit_form(self) -> AgentFormResult:
        """Submit the form to create a new agent."""
        request = self._build_create_request()
        response = await self._client.create_agent(request)

        return AgentFormResult(
            agent_id=str(response.id),
            agent_name=response.name,
            is_update=False,
        )

    def _build_create_request(self) -> CreateAgentRequest:
        """Build the CreateAgentRequest from form fields."""
        from textual.widgets import Input, TextArea

        # Required: name
        name = self.query_one("#name-input", Input).value.strip()

        # Required: models
        model_configs = self._build_model_configs()

        # Required for non-global: tags
        tag_picker = self.query_one("#tag-picker", TagPicker)
        tags = tag_picker.selected_tags

        # Basic info
        description = self.query_one("#description-input", Input).value.strip() or None
        scope = self._get_scope()

        # Base agent
        base_agent_picker = self.query_one("#base-agent-picker", AgentPicker)
        base_agent_id = self._parse_uuid(
            base_agent_picker.selected_agent_id, "Base Agent"
        )

        # System instruction template
        template_picker = self.query_one("#system-template-picker", TemplatePicker)
        system_instruction_version_id = self._parse_uuid(
            template_picker.selected_id, "System Template"
        )

        # Schemas
        output_schema_picker = self.query_one("#output-schema-picker", SchemaPicker)
        output_schema_id = self._parse_uuid(
            output_schema_picker.selected_id, "Output Schema"
        )

        # Output schema from JSON builder
        output_schema = self._get_output_schema()

        # Generation parameters
        gen_params = self._build_generation_params()

        # Advanced: default headers
        default_headers = self._parse_json(
            self.query_one("#default-headers-textarea", TextArea).text,
            "Default Headers",
        )

        return CreateAgentRequest(
            name=name,
            models=model_configs,
            tags=tags,
            scope=scope,
            base_agent_id=base_agent_id,
            description=description,
            system_instruction_version_id=system_instruction_version_id,
            output_schema_id=output_schema_id,
            output_schema=output_schema,
            default_request_headers=default_headers,
            generation_params=gen_params,
            tools=self._build_tools(),
        )
