""".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 key: openai
            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'}",
        ]

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

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

        lines.append("")

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

        os.chmod(env_path, 0o600)

        return env_path
