"""Step 8: Set environment variables (OPENROUTER_API_KEY, OPENAI_API_KEY)."""

from __future__ import annotations

from easyclaw_tui.steps.base import BaseStep, StepResult


class EnvVarsStep(BaseStep):
    STEP_NUM = 8
    STEP_NAME = "Env Vars"

    async def run(self) -> StepResult:
        if not self.state.openrouter_key:
            self.warn("No OpenRouter key to set")
            return StepResult(True)

        await self._set_env("OPENROUTER_API_KEY", self.state.openrouter_key)

        if self.state.openai_key:
            await self._set_env("OPENAI_API_KEY", self.state.openai_key)

        return StepResult(True)

    async def _set_env(self, key: str, value: str) -> None:
        """Add or update env var in ~/.bashrc and export it."""
        # Check if already set
        rc, _, _ = await self.run_cmd(f'grep -q "^export {key}=" ~/.bashrc 2>/dev/null')
        if rc == 0:
            # Update existing
            escaped_val = value.replace("/", "\\/").replace("&", "\\&")
            await self.run_cmd(
                f'sed -i "s|^export {key}=.*|export {key}=\\"{value}\\"|" ~/.bashrc'
            )
            self.ok(f"Updated {key} in ~/.bashrc")
        else:
            # Add new
            await self.run_cmd(f'echo \'export {key}="{value}"\' >> ~/.bashrc')
            self.ok(f"Added {key} to ~/.bashrc")
