"""Configuration helpers for a24wh."""

import os
from dataclasses import dataclass

from .constants import (
    AUTO_CONFIGURE_LOGGING_ENV_VAR,
    DEFAULT_REQUEST_DELAY,
    DEFAULT_LOG_FILE,
    DEFAULT_LOG_LEVEL,
    DEFAULT_RETRY_COUNT,
    DEFAULT_RETRY_DELAY,
    DEFAULT_TIMEOUT,
    DEFAULT_WEBHOOK_ENV_VAR,
    LOG_FILE_ENV_VAR,
    LOG_LEVEL_ENV_VAR,
    LOG_TO_CONSOLE_ENV_VAR,
    LOG_TO_FILE_ENV_VAR,
    REQUEST_DELAY_ENV_VAR,
    RETRY_COUNT_ENV_VAR,
    RETRY_DELAY_ENV_VAR,
    TIMEOUT_ENV_VAR,
    )


def _env_str(name: str, default: str = "") -> str:
    return (os.getenv(name, default) or default).strip()


def _env_bool(name: str, default: bool = False) -> bool:
    value = _env_str(name)
    if not value:
        return default
    return value.lower() in {"1", "true", "yes", "on"}


def _env_int(name: str, default: int) -> int:
    value = _env_str(name)
    if not value:
        return default
    try:
        return int(value)
    except (TypeError, ValueError):
        return default


def _env_float(name: str, default: float) -> float:
    value = _env_str(name)
    if not value:
        return default
    try:
        return float(value)
    except (TypeError, ValueError):
        return default


@dataclass(frozen=True)
class A24WHConfig:
    default_webhook_env_var: str = DEFAULT_WEBHOOK_ENV_VAR
    default_timeout: int = DEFAULT_TIMEOUT
    retry_count: int = DEFAULT_RETRY_COUNT
    retry_delay: float = DEFAULT_RETRY_DELAY
    request_delay: float = DEFAULT_REQUEST_DELAY
    auto_configure_logging: bool = False
    log_level: str = DEFAULT_LOG_LEVEL
    log_to_console: bool = False
    log_to_file: bool = False
    log_file: str = DEFAULT_LOG_FILE


def get_config() -> A24WHConfig:
    return A24WHConfig(
        default_webhook_env_var=DEFAULT_WEBHOOK_ENV_VAR,
        default_timeout=_env_int(TIMEOUT_ENV_VAR, DEFAULT_TIMEOUT),
        retry_count=max(0, _env_int(RETRY_COUNT_ENV_VAR, DEFAULT_RETRY_COUNT)),
        retry_delay=max(0.0, _env_float(RETRY_DELAY_ENV_VAR, DEFAULT_RETRY_DELAY)),
        request_delay=max(0.0, _env_float(REQUEST_DELAY_ENV_VAR, DEFAULT_REQUEST_DELAY)),
        auto_configure_logging=_env_bool(AUTO_CONFIGURE_LOGGING_ENV_VAR, False),
        log_level=_env_str(LOG_LEVEL_ENV_VAR, DEFAULT_LOG_LEVEL).upper(),
        log_to_console=_env_bool(LOG_TO_CONSOLE_ENV_VAR, True),
        log_to_file=_env_bool(LOG_TO_FILE_ENV_VAR, False),
        log_file=_env_str(LOG_FILE_ENV_VAR, DEFAULT_LOG_FILE) or DEFAULT_LOG_FILE,
        )


def get_default_webhook_url() -> str:
    config = get_config()
    return _env_str(config.default_webhook_env_var)
