"""Default constants and config merge for TgrEzLi."""
from __future__ import annotations

from typing import Any

from TgrEzLi.types import ApiServerConfig, ConnectionConfig, LoggingConfig, TgrEzLiConfig

# API server
DEFAULT_API_HOST = "localhost"
DEFAULT_API_PORT = 9999
MAX_REQUEST_BODY_BYTES = 1 * 1024 * 1024  # 1 MiB

# Logging (save_log_file default False)
DEFAULT_LOG_FILE_PATH = "TgrEzLi.log"
DEFAULT_LOGGER_NAME = "TgrEzLi"
DEFAULT_SAVE_LOG_FILE = False
DEFAULT_DEBUG = False

# Credentials (crypto) – used only by .signup() / .login()
DEFAULT_CREDENTIAL_FILE = "tgrdata.cy"


# Default config layers
DEFAULT_LOGGING: LoggingConfig = {
    "debug": DEFAULT_DEBUG,
    "save_log_file": DEFAULT_SAVE_LOG_FILE,
    "log_file_path": DEFAULT_LOG_FILE_PATH,
}
DEFAULT_CONNECTION: ConnectionConfig = {}
DEFAULT_API_SERVER: ApiServerConfig = {
    "host": DEFAULT_API_HOST,
    "port": DEFAULT_API_PORT,
}


def merge_config(user: TgrEzLiConfig | None) -> dict[str, Any]:
    """Merge user config with defaults. Returns a plain dict for internal use."""
    if not user:
        return {
            "connection": dict(DEFAULT_CONNECTION),
            "logging": dict(DEFAULT_LOGGING),
            "api_server": dict(DEFAULT_API_SERVER),
        }
    out: dict[str, Any] = {}
    out["connection"] = {**DEFAULT_CONNECTION, **(user.get("connection") or {})}
    out["logging"] = {**DEFAULT_LOGGING, **(user.get("logging") or {})}
    out["api_server"] = {**DEFAULT_API_SERVER, **(user.get("api_server") or {})}
    return out
