"""Auto-populate server context attached to every event."""

from __future__ import annotations

import os
import platform
import socket
import sys
from typing import Any

from .types import SDKOptions, ServerContext

__version__ = "0.1.0"


def build_server_context(options: SDKOptions) -> ServerContext:
    """Build a :class:`ServerContext` dict from the current environment."""

    implementation = platform.python_implementation().lower()
    runtime: str
    if implementation == "cpython":
        runtime = "cpython"
    elif implementation == "pypy":
        runtime = "pypy"
    else:
        runtime = "unknown"

    try:
        host: str | None = socket.gethostname()
    except Exception:
        host = None

    environment = os.environ.get(
        "ENV",
        os.environ.get(
            "ENVIRONMENT",
            os.environ.get("DJANGO_ENV", "unknown"),
        ),
    )

    opts: dict[str, Any] = dict(options)  # type: ignore[arg-type]

    return {
        "server": {
            "runtime": runtime,  # type: ignore[typeddict-item]
            "python_version": sys.version.split()[0],
            "environment": environment,
            "service_name": opts.get("service_name"),
            "service_version": opts.get("service_version"),
            "host": host,
        },
        "sdk": {
            "name": "kanban-analytics",
            "version": __version__,
        },
    }
