"""
Environment variable validation for Slack MCP Server.

Required environment variables:
    SLACK_BOT_TOKEN:      Bot User OAuth Token (xoxb-...)
    SLACK_USER_TOKEN:     User OAuth Token (xoxp-...) — needed for search.messages
    SLACK_SIGNING_SECRET: Signing secret for request verification

Optional:
    SLACK_LOG_LEVEL:      Logging level (default: INFO)
"""

import os
import sys
import logging

logger = logging.getLogger("slack_mcp_server.config")


class SlackConfig:
    """Validated Slack configuration from environment variables."""

    def __init__(self):
        self.bot_token: str = ""
        self.user_token: str = ""
        self.signing_secret: str = ""
        self.log_level: str = "INFO"
        self._load()

    def _load(self):
        self.bot_token = os.environ.get("SLACK_BOT_TOKEN", "")
        self.user_token = os.environ.get("SLACK_USER_TOKEN", "")
        self.signing_secret = os.environ.get("SLACK_SIGNING_SECRET", "")
        self.log_level = os.environ.get("SLACK_LOG_LEVEL", "INFO")

    def validate(self) -> list[str]:
        """Validate configuration. Returns list of error messages (empty = valid)."""
        errors = []

        if not self.bot_token:
            errors.append("SLACK_BOT_TOKEN is required (xoxb-...)")
        elif not self.bot_token.startswith("xoxb-"):
            errors.append(
                f"SLACK_BOT_TOKEN should start with 'xoxb-', got '{self.bot_token[:8]}...'"
            )

        if self.user_token and not self.user_token.startswith("xoxp-"):
            errors.append(
                f"SLACK_USER_TOKEN should start with 'xoxp-', got '{self.user_token[:8]}...'"
            )

        # signing_secret and user_token are optional for basic operation
        if not self.user_token:
            logger.warning(
                "SLACK_USER_TOKEN not set — search.messages will use bot token (may have limited results)"
            )

        if not self.signing_secret:
            logger.warning(
                "SLACK_SIGNING_SECRET not set — request verification disabled"
            )

        return errors

    def validate_or_exit(self):
        """Validate configuration, exit with clear error if invalid."""
        errors = self.validate()
        if errors:
            print("Slack MCP Server configuration errors:", file=sys.stderr)
            for err in errors:
                print(f"  ✗ {err}", file=sys.stderr)
            print(
                "\nSet the required environment variables and try again.",
                file=sys.stderr,
            )
            sys.exit(1)
        logger.info("Slack configuration validated successfully")
