"""Step 5: Collect configuration — minimal prompt for OpenRouter key."""

from __future__ import annotations

from easyclaw_tui.steps.base import BaseStep, StepResult
from easyclaw_tui.state import MODEL_MAP

# Free model on OpenRouter (no billing required, just an account)
FREE_MODEL = "meta-llama/llama-3.1-8b-instruct:free"
FREE_MODEL_NAME = "Llama 3.1 8B (free)"


class ConfigStep(BaseStep):
    """Configuration step.

    If the OpenRouter key is already provided via CLI, auto-continues.
    Otherwise shows a minimal single-field prompt.
    If skipped, defaults to a free model.
    """

    STEP_NUM = 5
    STEP_NAME = "Config"

    async def run(self) -> StepResult:
        if self.state.openrouter_key:
            # Key provided via CLI — skip form entirely
            self.ok("OpenRouter key provided")
        else:
            # Ask for just the OpenRouter key — minimal interaction
            self.info("OpenRouter API key needed for your AI agent.")
            self.info("Get a free key at: https://openrouter.ai/keys")
            self.info("")

            from easyclaw_tui.widgets.config_form import KeyPrompt

            prompt = KeyPrompt()
            await self.panel.show_form(prompt)
            await self.panel.wait_for_submit()

            self.state.openrouter_key = prompt.key_value
            await self.panel.clear_form()

        # If still no key, switch to free model
        if not self.state.openrouter_key:
            self.warn("No OpenRouter key — using free model")
            self.state.model = FREE_MODEL_NAME
            self.state.model_path = f"openrouter/{FREE_MODEL}"
            self.state.fallback_path = f"openrouter/{FREE_MODEL}"
        else:
            if not self.state.openrouter_key.startswith("sk-or-"):
                self.warn("Key should start with 'sk-or-' — continuing anyway")
            self.ok(f"OpenRouter key: {self.state.openrouter_key[:12]}...")

            # Resolve model paths from defaults
            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"

        # Log final config
        if self.state.api_key:
            self.ok(f"API key: {self.state.api_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")
        else:
            self.info("Memory search: disabled (no OpenAI key)")

        return StepResult(True)
