from __future__ import annotations

from atlas_runner.docker_backend import DockerBackend
from atlas_runner.errors import ErrorCode, RunnerError
from atlas_runner.models import ContainerStatus, RunResult, RunSpec
from atlas_runner.protocol import RunnerBackend


def create_backend(
    backend_type: str = "docker",
    docker_host: str | None = None,
) -> RunnerBackend:
    """Factory that returns a backend instance for the given type."""
    if backend_type == "docker":
        return DockerBackend(docker_host=docker_host)
    raise RunnerError(
        code=ErrorCode.BACKEND_ERROR,
        message=f"Unknown backend type: {backend_type}",
    )


class Runner:
    """High-level facade wrapping a ``RunnerBackend``."""

    def __init__(self, backend: RunnerBackend) -> None:
        self._backend = backend

    def login(self, registry: str, username: str, password: str) -> None:
        self._backend.login(registry, username, password)

    def pull(self, image: str) -> None:
        self._backend.pull(image)

    def run(self, spec: RunSpec) -> RunResult:
        return self._backend.run(spec)

    def stop(self, name: str) -> None:
        self._backend.stop(name)

    def destroy(self, name: str) -> None:
        """Stop and remove a container (idempotent)."""
        self._backend.stop(name)
        self._backend.rm(name)

    def status(self, name: str) -> ContainerStatus:
        return self._backend.inspect(name)

    def logs(self, name: str) -> str:
        return self._backend.logs(name)

    def ps(self) -> list[ContainerStatus]:
        return self._backend.ps()
