"""Step 5: Collect configuration — interactive form with Input/Select widgets."""

from __future__ import annotations

from easyclaw_tui.steps.base import BaseStep, StepResult
from easyclaw_tui.state import MODEL_MAP
from easyclaw_tui.widgets.config_form import ConfigForm


class ConfigStep(BaseStep):
    """Interactive configuration step.

    Shows a form with Input fields for API keys and Select dropdowns
    for model, channel, and bind mode. Pauses execution until the
    user fills in values and clicks Continue.
    """

    STEP_NUM = 5
    STEP_NAME = "Config"

    async def run(self) -> StepResult:
        self.info("Fill in your configuration below and click Continue.")

        # Create the form, pre-filled with any CLI-provided values
        form = ConfigForm(
            api_key=self.state.api_key,
            openrouter_key=self.state.openrouter_key,
            openai_key=self.state.openai_key,
            model=self.state.model,
            channel=self.state.channel,
            bind=self.state.bind,
        )

        # Mount form and wait for submission
        await self.panel.show_form(form)
        await self.panel.wait_for_submit()

        # Read values from form
        self.state.api_key = form.api_key
        self.state.openrouter_key = form.openrouter_key
        self.state.openai_key = form.openai_key
        self.state.model = form.model
        self.state.channel = form.channel
        self.state.bind = form.bind

        # Clear the form
        await self.panel.clear_form()

        # Resolve model paths
        self.state.model_path = MODEL_MAP.get(
            self.state.model, f"openrouter/{self.state.model}"
        )
        if "haiku" in self.state.model:
            self.state.fallback_path = "openrouter/deepseek/deepseek-v3.2"
        else:
            self.state.fallback_path = "openrouter/anthropic/claude-haiku-4.5"

        # Validate and log
        if self.state.api_key:
            if not self.state.api_key.startswith("ec_live_"):
                self.warn("API key should start with 'ec_live_'")
            self.ok(f"API key: {self.state.api_key[:12]}...")
        else:
            self.warn("No API key — Foreman chat disabled")

        if not self.state.openrouter_key.startswith("sk-or-"):
            self.warn("OpenRouter key should start with 'sk-or-'")
        self.ok(f"OpenRouter key: {self.state.openrouter_key[:12]}...")

        self.ok(f"Model: {self.state.model}")
        self.ok(f"Bind: {self.state.bind}")
        self.ok(f"Channel: {self.state.channel}")

        if self.state.openai_key:
            self.state.memory_enabled = True
            self.ok("Memory search: enabled (OpenAI)")
        else:
            self.info("Memory search: disabled (no OpenAI key)")

        return StepResult(True)
