"""Keycloak Admin Configuration

Configuration for Keycloak service account used for role management.

Author: Balázs Milán (milan.balazs@uni-obuda.hu)
"""

import os
from typing import Optional
from dataclasses import dataclass


@dataclass
class KeycloakAdminConfig:
    """Configuration for Keycloak Admin API.

    Service account credentials for role management operations.

    Attributes:
        server_url: Keycloak server URL (e.g., "https://keycloak.company.com/auth")
        realm_name: Realm name (e.g., "blackant")
        client_id: Service account client ID
        client_secret: Service account client secret
        verify_ssl: Whether to verify SSL certificates
        timeout: Request timeout in seconds
    """

    server_url: str
    realm_name: str
    client_id: str
    client_secret: str
    verify_ssl: bool = True
    timeout: int = 30

    @classmethod
    def from_env(cls) -> 'KeycloakAdminConfig':
        """Create configuration from environment variables.

        Required environment variables:
        - KEYCLOAK_SERVER_URL: Keycloak server URL
        - KEYCLOAK_REALM: Realm name
        - KEYCLOAK_ADMIN_CLIENT_ID: Service account client ID
        - KEYCLOAK_ADMIN_CLIENT_SECRET: Service account client secret

        Optional:
        - KEYCLOAK_VERIFY_SSL: "true" or "false" (default: true)
        - KEYCLOAK_TIMEOUT: Timeout in seconds (default: 30)

        Returns:
            KeycloakAdminConfig instance

        Raises:
            ValueError: If required environment variables are missing
        """
        server_url = os.getenv('KEYCLOAK_SERVER_URL')
        realm_name = os.getenv('KEYCLOAK_REALM')
        client_id = os.getenv('KEYCLOAK_ADMIN_CLIENT_ID')
        client_secret = os.getenv('KEYCLOAK_ADMIN_CLIENT_SECRET')

        # Validate required vars
        missing = []
        if not server_url:
            missing.append('KEYCLOAK_SERVER_URL')
        if not realm_name:
            missing.append('KEYCLOAK_REALM')
        if not client_id:
            missing.append('KEYCLOAK_ADMIN_CLIENT_ID')
        if not client_secret:
            missing.append('KEYCLOAK_ADMIN_CLIENT_SECRET')

        if missing:
            raise ValueError(
                f"Missing required environment variables: {', '.join(missing)}"
            )

        # Optional vars
        verify_ssl = os.getenv('KEYCLOAK_VERIFY_SSL', 'true').lower() == 'true'
        timeout = int(os.getenv('KEYCLOAK_TIMEOUT', '30'))

        return cls(
            server_url=server_url,
            realm_name=realm_name,
            client_id=client_id,
            client_secret=client_secret,
            verify_ssl=verify_ssl,
            timeout=timeout
        )

    def validate(self) -> None:
        """Validate configuration values.

        Raises:
            ValueError: If configuration is invalid
        """
        if not self.server_url.startswith(('http://', 'https://')):
            raise ValueError(
                f"Invalid server URL: {self.server_url} "
                "(must start with http:// or https://)"
            )

        if len(self.client_secret) < 16:
            raise ValueError(
                "Client secret must be at least 16 characters long"
            )

        if self.timeout < 1 or self.timeout > 300:
            raise ValueError("Timeout must be between 1 and 300 seconds")
