"""Step 5: Configuration — auto-configures with built-in free key or user-provided key."""

from __future__ import annotations

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


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

    Uses the built-in OpenRouter key (free model) by default.
    If the user provides their own key via --openrouter-key, uses that
    with their chosen model instead. Zero interaction required.
    """

    STEP_NUM = 5
    STEP_NAME = "Config"

    async def run(self) -> StepResult:
        if self.state.openrouter_key:
            # User provided their own key — use their model choice
            self.ok("Using your OpenRouter key")
            if not self.state.openrouter_key.startswith("sk-or-"):
                self.warn("Key should start with 'sk-or-' — continuing anyway")

            model = self.state.model or "minimax-m2.5"
            self.state.model = model
            self.state.model_path = MODEL_MAP.get(
                model, f"openrouter/{model}"
            )
            if "haiku" in model:
                self.state.fallback_path = "openrouter/deepseek/deepseek-v3.2"
            else:
                self.state.fallback_path = "openrouter/anthropic/claude-haiku-4.5"
        else:
            # No key provided — use built-in free key + free model
            self.state.openrouter_key = InstallState.BUILTIN_OR_KEY
            self.state.model = InstallState.BUILTIN_MODEL_NAME
            self.state.model_path = f"openrouter/{InstallState.BUILTIN_MODEL}"
            self.state.fallback_path = f"openrouter/{InstallState.BUILTIN_MODEL}"
            self.ok("Using built-in free model (Arcee Trinity Large)")
            self.info("Upgrade anytime by setting OPENROUTER_API_KEY")

        # Log final config
        if self.state.api_key:
            self.ok(f"EasyClaw 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)
