""".env file generation for Optix configuration."""

import os
from pathlib import Path


class EnvWriter:
    """Writer for .env configuration files."""

    def get_env_path(self, scope: str) -> Path:
        """Get the .env file path based on scope.

        Args:
            scope: "global" or "local"

        Returns:
            Path to the .env file
        """
        if scope == "global":
            optix_dir = Path.home() / ".optix"
            optix_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
            return optix_dir / ".env"
        else:
            return Path(".env")

    def write(
        self,
        scope: str,
        api_keys: dict[str, str],
        expert_enabled: bool,
        dashboard_enabled: bool = False,
        dashboard_port: int = 24282,
    ) -> Path:
        """Write .env file with configuration.

        Args:
            scope: "global" or "local"
            api_keys: Dict with keys: openai, gemini, anthropic
            expert_enabled: Whether expert analysis is enabled
            dashboard_enabled: Whether dashboard UI is enabled
            dashboard_port: Port for dashboard (default 24282)

        Returns:
            Path to the created .env file
        """
        env_path = self.get_env_path(scope)

        lines = [
            "# Optix MCP Server Configuration",
            "# Generated by installation wizard",
            "",
            "# Server Settings",
            "SERVER_NAME=optix-mcp-server",
            "LOG_LEVEL=INFO",
            "TRANSPORT=stdio",
            "",
            "# Expert Analysis",
            f"EXPERT_ANALYSIS_ENABLED={'true' if expert_enabled else 'false'}",
        ]

        provider = None

        if api_keys.get("openai"):
            if not provider:
                provider = "openai"
            lines.append(f"OPENAI_API_KEY={api_keys['openai']}")

        if api_keys.get("gemini"):
            if not provider:
                provider = "gemini"
            lines.append(f"GEMINI_API_KEY={api_keys['gemini']}")

        if api_keys.get("anthropic"):
            if not provider:
                provider = "anthropic"
            lines.append(f"ANTHROPIC_API_KEY={api_keys['anthropic']}")

        if provider:
            lines.append(f"OPTIX_LLM_PROVIDER={provider}")

        lines.extend([
            "",
            "# Dashboard Settings",
            f"OPTIX_DASHBOARD_ENABLED={'true' if dashboard_enabled else 'false'}",
        ])
        if dashboard_enabled:
            lines.append(f"OPTIX_DASHBOARD_PORT={dashboard_port}")

        lines.append("")

        env_path.write_text("\n".join(lines))

        os.chmod(env_path, 0o600)

        return env_path
