from docker import errors
from docker.models.containers import Container

from .types import SerializedContainer


def container_logs(container: Container, tail: int) -> str | None:
    try:
        return container.logs(tail=tail).decode()
    except errors.APIError:
        return None


def serialize_container(container: Container) -> SerializedContainer:
    return SerializedContainer(
        id=container.short_id,
        name=container.name,
        image=container.image.tags[0] if container.image else None,
        labels=container.labels,
        status=container.status,
        health=container.health,
        engine=container.labels.get("engine"),
        owner=container.labels.get("owner"),
        environment=container.attrs["Config"]["Env"],
        logs=container_logs(container, 100),
    )